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
7efd76ef0420bd1ad3fff4d7fb25bb17
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader bf; static PrintWriter out; static Scanner sc; static StringTokenizer st; // static long mod = (long)(1e9+7); static long mod = 998244353; static long fact[]; static long inverse[]; public static void main (String[] args)throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new Scanner(System.in); fact = new long[65]; inverse = new long[65]; fact[0] = 1; inverse[0] = 1; for(int i = 1;i<fact.length;i++){ fact[i] = (fact[i-1] * i)%mod; inverse[i] = binaryExpo(fact[i], mod-2); } int t = nextInt(); while(t-->0){ solve(); } out.flush(); } public static void solve()throws IOException{ int n = nextInt(); int k = nextInt(); List<List<Integer>>list = new ArrayList<>(); for(int i =0;i<=n;i++){ list.add(new ArrayList<>()); } for(int i =0;i<n-1;i++){ int u = i+2; int v = nextInt(); list.get(u).add(v); list.get(v).add(u); } List<int[]>leaf = new ArrayList<>(); int[][]parent = new int[n+1][19]; int[]max = new int[1]; dfs(list,1,-1,parent,1,leaf,max); for(int j = 1;j<=n;j++){ for(int i = 1;i<=18;i++){ int x = parent[j][i-1]; if(x == -1){ parent[j][i] = -1; } else{ parent[j][i] = parent[x][i-1]; } } } int l = 2; int r = max[0]; int ans = r; while(l<=r){ int mid = (l + r)/2; PriorityQueue<int[]>pq = new PriorityQueue<>((a,b)->(b[1] - a[1])); boolean[]in = new boolean[n+1]; for(int i = 0;i<leaf.size();i++){ pq.offer(new int[]{leaf.get(i)[0],leaf.get(i)[1]}); in[leaf.get(i)[0]] = true; } int op = k; boolean[]canOp = new boolean[n+1]; while(op > 0 && !pq.isEmpty()){ while(!pq.isEmpty() && (canOp[pq.peek()[0]] || pq.peek()[1] <= mid))pq.poll(); if(!pq.isEmpty()){ int up = mid - 2; int[]cur = pq.poll(); int p = findP(parent,cur[0],up); int upP = parent[p][0]; if(upP != -1){ if(!in[upP]){ in[upP] = true; pq.offer(new int[]{upP,cur[1] - (mid - 1)}); } } recursion(list,p,upP,canOp); op--; } } while(!pq.isEmpty() && (pq.peek()[1] <= mid || canOp[pq.peek()[0]]))pq.poll(); if(pq.isEmpty()){ ans = mid; r = mid-1; } else{ l = mid+1; } } out.println(ans - 1); } public static void recursion(List<List<Integer>>list,int cur,int parent,boolean[]canOp){ if(canOp[cur])return; List<Integer>temp = list.get(cur); canOp[cur] = true; for(int i = 0;i<temp.size();i++){ int next = temp.get(i); if(next != parent){ recursion(list,next,cur,canOp); } } } public static int findP(int[][]parent,int cur,int k){ for(int i = 0;i<=18;i++){ if(((1<<i)&k) != 0)cur = parent[cur][i]; } return cur; } public static void dfs(List<List<Integer>>list,int cur,int p,int [][]parent,int depth,List<int[]>leaf,int[]max){ parent[cur][0] = p; boolean check = false; List<Integer>temp = list.get(cur); for(int i = 0;i<temp.size();i++){ int next = temp.get(i); if(p != next){ check = true; dfs(list,next,cur,parent,depth+1,leaf,max); } } if(!check){ leaf.add(new int[]{cur,depth}); } if(max[0] < depth)max[0] = depth; } public static int compare(String a , String b){ if(a.compareTo(b) < 0)return -1; if(a.compareTo(b) > 0)return 1; return 0; } public static void req(long l,long r){ out.println("? " + l + " " + r); out.flush(); } public static long nck(int n,int k){ return ((fact[n] * (inverse[n-k])%mod) * inverse[k])%mod; } public static long binaryExpo(long base,long expo){ if(expo == 0)return 1; long val; if(expo%2 == 1){ val = (binaryExpo(base, expo/2)); val = (val * val)%mod; val = (val * base)%mod; } else{ val = binaryExpo(base, expo/2); val = (val*val)%mod; } return (val%mod); } public static boolean isSorted(int[]arr){ for(int i =1;i<arr.length;i++){ if(arr[i] < arr[i-1]){ return false; } } return true; } //function to find the topological sort of the a DAG public static boolean hasCycle(int[]indegree,List<List<Integer>>list,int n,List<Integer>topo){ Queue<Integer>q = new LinkedList<>(); for(int i =1;i<indegree.length;i++){ if(indegree[i] == 0){ q.add(i); topo.add(i); } } while(!q.isEmpty()){ int cur = q.poll(); List<Integer>l = list.get(cur); for(int i = 0;i<l.size();i++){ indegree[l.get(i)]--; if(indegree[l.get(i)] == 0){ q.add(l.get(i)); topo.add(l.get(i)); } } } if(topo.size() == n)return false; return true; } // function to find the parent of any given node with path compression in DSU public static int find(int val,int[]parent){ if(val == parent[val])return val; return parent[val] = find(parent[val],parent); } // function to connect two components public static void union(int[]rank,int[]parent,int u,int v){ int a = find(u,parent); int b= find(v,parent); if(a == b)return; if(rank[a] == rank[b]){ parent[b] = a; rank[a]++; } else{ if(rank[a] > rank[b]){ parent[b] = a; } else{ parent[a] = b; } } } // public static int findN(int n){ int num = 1; while(num < n){ num *=2; } return num; } // code for input public static void print(String s ){ System.out.print(s); } public static void print(int num ){ System.out.print(num); } public static void print(long num ){ System.out.print(num); } public static void println(String s){ System.out.println(s); } public static void println(int num){ System.out.println(num); } public static void println(long num){ System.out.println(num); } public static void println(){ System.out.println(); } public static int Int(String s){ return Integer.parseInt(s); } public static long Long(String s){ return Long.parseLong(s); } public static String[] nextStringArray()throws IOException{ return bf.readLine().split(" "); } public static String nextString()throws IOException{ return bf.readLine(); } public static long[] nextLongArray(int n)throws IOException{ String[]str = bf.readLine().split(" "); long[]arr = new long[n]; for(int i =0;i<n;i++){ arr[i] = Long.parseLong(str[i]); } return arr; } public static int[][] newIntMatrix(int r,int c)throws IOException{ int[][]arr = new int[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Integer.parseInt(str[j]); } } return arr; } public static long[][] newLongMatrix(int r,int c)throws IOException{ long[][]arr = new long[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Long.parseLong(str[j]); } } return arr; } static class pair{ int one; int two; pair(int one,int two){ this.one = one ; this.two =two; } } public static long gcd(long a,long b){ if(b == 0)return a; return gcd(b,a%b); } public static long lcm(long a,long b){ return (a*b)/(gcd(a,b)); } public static boolean isPalindrome(String s){ int i = 0; int j = s.length()-1; while(i<=j){ if(s.charAt(i) != s.charAt(j)){ return false; } i++; j--; } return true; } // these functions are to calculate the number of smaller elements after self public static void sort(int[]arr,int l,int r){ if(l < r){ int mid = (l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); smallerNumberAfterSelf(arr, l, mid, r); } } public static void smallerNumberAfterSelf(int[]arr,int l,int mid,int r){ int n1 = mid - l +1; int n2 = r - mid; int []a = new int[n1]; int[]b = new int[n2]; for(int i = 0;i<n1;i++){ a[i] = arr[l+i]; } for(int i =0;i<n2;i++){ b[i] = arr[mid+i+1]; } int i = 0; int j =0; int k = l; while(i<n1 && j < n2){ if(a[i] < b[j]){ arr[k++] = a[i++]; } else{ arr[k++] = b[j++]; } } while(i<n1){ arr[k++] = a[i++]; } while(j<n2){ arr[k++] = b[j++]; } } public static String next(){ while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bf.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static String nextLine(){ String str = ""; try { str = bf.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // use some math tricks it might help // sometimes just try to think in straightforward plan in A and B problems don't always complecate the questions with thinking too much differently // always use long number to do 10^9+7 modulo // if a problem is related to binary string it could also be related to parenthesis // *****try to use binary search(it is a very beautiful thing it can work in some of the very unexpected problems ) in the question it might work****** // try sorting // try to think in opposite direction of question it might work in your way // if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+d or a,b,c,d in general // if the question is to much related to left and/or right side of any element in an array then try monotonic stack it could work. // in range query sums try to do binary search it could work // analyse the time complexity of program thoroughly // anylyse the test cases properly // if we divide any number by 2 till it gets 1 then there will be (number - 1) operation required // try to do the opposite operation of what is given in the problem //think about the base cases properly //If a question is related to numbers try prime factorisation or something related to number theory // keep in mind unique strings //you can calculate the number of inversion in O(n log n) // in a matrix you could sometimes think about row and cols indenpendentaly. // Try to think in more constructive(means a way to look through various cases of a problem) way. // observe the problem carefully the answer could be hidden in the given test cases itself. (A, B , C); // when we have equations like (a+b = N) and we have to find the max of (a*b) then the values near to the N/2 must be chosen as (a and b); // give emphasis to the number of occurences of elements it might help. // if a number is even then we can find the pair for each and every number in that range whose bitwise AND is zero. // if a you find a problem related to the graph make a graph // There is atleast one prime number between the interval [n , 3n/2]; // If a problem is related to maths then try to form an mathematical equation. // you can create any sum between (n * (n + 1)/2) with first n natural numbers.
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
2d4ed22ff2016f30199bdfe82d67ba38
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
// OM NAMAH SHIVAY // 27 days remaining(2609) import java.math.BigInteger; import java.util.*; import java.io.*; public class Vaibhav { static boolean prime[]; static class Pair implements Comparable<Pair> {int a;int b;Pair(int a, int b) {this.a = a;this.b = b;}public boolean equals(Object o) {if (o instanceof Pair) {Pair p = (Pair) o;return p.a == a && p.b == b;}return false;}public int hashCode() {int hash = 5;hash = 17 * hash + this.a;return hash;}public int compareTo(Pair o){if(this.a!=o.a)return this.a-o.a;else return this.b-o.b;}} static long power(long x, long y, long p) {if (y == 0) return 1;if (x == 0) return 0;long res = 1l;x = x % p;while (y > 0) {if (y % 2 == 1) res = (res * x) % p;y = y >> 1;x = (x * x) % p;}return res;} static void sort(long[] a) {ArrayList<Long> l = new ArrayList<>();for (long i : a) l.add(i);Collections.sort(l);for (int i = 0; i < a.length; i++) a[i] = l.get(i);} static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in));StringTokenizer st = new StringTokenizer("");String next() {while (!st.hasMoreTokens()) try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}return st.nextToken();}int nextInt() {return Integer.parseInt(next());}double nextDouble() {return Double.parseDouble(next());}int[] readArray(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = nextInt();return a;}long[] readlongArray(int n) {long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nextLong();return a;}long nextLong() {return Long.parseLong(next());}} static void sieveOfEratosthenes(int n) {prime = new boolean[n + 1];for (int i = 0; i <= n; i++) prime[i] = true;for (int p = 2; p * p <= n; p++) {if (prime[p] == true) {for (int i = p * p; i <= n; i += p) prime[i] = false;}}} public static int log2(int x) { return (int) (Math.log(x) / Math.log(2)); } static long binomialCoeff(long n, long r) {if (r > n) return 0l;long m = 998244353l;long inv[] = new long[(int) r + 1];inv[0] = 1;if (r + 1 >= 2)inv[1] = 1;for (int i = 2; i <= r; i++) {inv[i] = m - (m / i) * inv[(int) (m % i)] % m;}long ans = 1l;for (int i = 2; i <= r; i++) {ans = (int) (((ans % m) * (inv[i] % m)) % m);}for (int i = (int) n; i >= (n - r + 1); i--) {ans = (int) (((ans % m) * (i % m)) % m);}return ans;} public static long gcd(long a, long b) {if (b == 0) {return a;}return gcd(b, a % b);} static BigInteger bi(String str) { return new BigInteger(str); } // Author - vaibhav_1710 static FastScanner fs = null; static long mod = 1_000_000_007; static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}, }; static int k; static long dp[][]; static ArrayList<Integer> al[]; static long m = 998244353l; static int n; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); outer: while (t-- > 0) { n = fs.nextInt(); k = fs.nextInt(); al = new ArrayList[n]; int p[] = fs.readArray(n-1); for(int i =0;i<n;i++){ al[i] = new ArrayList<>(); } for(int i=0;i<n-1;i++){ al[p[i]-1].add(i+1); } int l=1; int r = n; int ans=n; while(l<=r){ int mid = (l+r)/2; if(check(mid)){ ans = mid; r = mid-1; }else{ l = mid+1; } } out.println(ans); } out.close(); } static int level[]; static int count=0; public static boolean check(int mid){ level = new int[n]; count=0; dfs(0,mid); return count<=k; } public static void dfs(int child,int mh){ int maxn=0; for(int v:al[child]){ dfs(v,mh); if(level[v]!=mh) maxn = Math.max(maxn,level[v]); if(level[v]==mh && child!=0) count++; } if(maxn==mh){ level[child]=1; }else{ level[child] = maxn+1; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
e332f50d1d4ebcc82404ae6871f8a478
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class CodeForces { /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ public static void solve(int tCase) throws IOException { int n = sc.nextInt(); int k = sc.nextInt(); parent = new int[n+1]; tree = new ArrayList[n+1]; for(int i=0;i<=n;i++)tree[i] = new ArrayList<>(); binaryLift = new int[n+1][20]; for(int i=0;i<=n;i++)Arrays.fill(binaryLift[i],-1); for(int i = 2;i<=n;i++){ int x = sc.nextInt(); parent[i] = x; binaryLift[i][0] = x; tree[x].add(i); } for(int pow = 1;pow<20;pow++) for(int i=1;i<=n;i++){ int x = binaryLift[i][pow-1]; if(x==-1)continue; binaryLift[i][pow] = binaryLift[x][pow-1]; } height = new int[n+1]; q = new ArrayDeque<>(); traversal = new ArrayList<>(); q.add(1); while (!q.isEmpty()){ int x = q.poll(); height[x] = x == 1 ? 0 : (height[parent[x]] + 1); traversal.add(x); for(int y : tree[x])q.add(y); } Collections.reverse(traversal); int l = 1; int r = n ; int ans = -1; while (l<=r){ int mid = (l + r)/2; if(isPos(mid,k,n)){ ans = mid; r = mid-1; }else l= mid+1; } out.println(ans); } static int[] parent,height; static List<Integer> [] tree; static List<Integer> traversal; static Queue<Integer> q; static int[][] binaryLift; private static boolean isPos(int curr, int k, int n){ boolean [] visited = new boolean[n+1]; for(int x : traversal){ if(visited[x])continue; if(height[x] > curr){ int ancestor = liftUp(x,curr-1); dfs(ancestor,visited); k--; } } return k >=0; } private static int liftUp(int x, int k){ for(int pow = 19;pow >=0 && x >=0;pow--){ if(((k>>pow) & 1) == 1)x = binaryLift[x][pow]; } return x; } private static void dfs(int x, boolean[] visited){ if(visited[x])return; visited[x] = true; for(int y : tree[x])dfs(y,visited); } public static void main(String[] args) throws IOException { openIO(); int testCase = 1; testCase = sc.nextInt(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ /*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/ // public static long mod = (int) 1e9 + 7; public static long mod = 998244353; public static int inf_int = (int)1e9; public static long inf_long = (long)2e15; public static void _sort(int[] arr, boolean isAscending) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } public static void _sort(long[] arr, boolean isAscending) { int n = arr.length; List<Long> list = new ArrayList<>(); for (long ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // time : O(1), space : O(1) public static int _digitCount(long num,int base){ // this will give the # of digits needed for a number num in format : base return (int)(1 + Math.log(num)/Math.log(base)); } // time for pre-computation of factorial and inverse-factorial table : O(nlog(mod)) public static long[] factorial , inverseFact; public static void _ncr_precompute(int n){ factorial = new long[n+1]; inverseFact = new long[n+1]; factorial[0] = inverseFact[0] = 1; for (int i = 1; i <=n; i++) { factorial[i] = (factorial[i - 1] * i) % mod; inverseFact[i] = _modExpo(factorial[i], mod - 2); } } // time of factorial calculation after pre-computation is O(1) public static int _ncr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod); } public static int _npr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[n - r] % mod); } // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { while (a>0){ long x = a; a = b % a; b = x; } return b; } // lcm(a,b) * gcd(a,b) = a * b public static long _lcm(long a, long b) { return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _modExpo(long x, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans *= x; ans %= mod; n--; } else { x *= x; x %= mod; n >>= 1; } } return ans; } // function to find a/b under modulo mod. time : O(logn) public static long _modInv(long a,long b){ return (a * _modExpo(b,mod-2)) % mod; } //sieve or first divisor time : O(mx * log ( log (mx) ) ) public static int[] _seive(int mx){ int[] firstDivisor = new int[mx+1]; for(int i=0;i<=mx;i++)firstDivisor[i] = i; for(int i=2;i*i<=mx;i++) if(firstDivisor[i] == i) for(int j = i*i;j<=mx;j+=i) if(firstDivisor[j]==j)firstDivisor[j] = i; return firstDivisor; } static class Pair<K, V>{ K ff; V ss; public Pair(K ff, V ss) { this.ff = ff; this.ss = ss; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return ff.equals(pair.ff) && ss.equals(pair.ss); } @Override public int hashCode() { return Objects.hash(ff, ss); } @Override public String toString(){ return ff.toString()+" "+ss.toString(); } } /*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/ /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException { sc = new FastestReader(); out = new PrintWriter(System.out); } public static void closeIO() throws IOException { out.flush(); out.close(); sc.close(); } private static final class FastestReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public FastestReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastestReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) {} return b; } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); final boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); return neg?-ret: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'); return neg?-ret: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); return neg?-ret:ret; } public String nextLine() throws IOException { final byte[] buf = new byte[(1<<10)]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { din.close(); } } /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/ } /** Some points to keep in mind : * 1. don't use Arrays.sort(primitive data type array) * 2. try to make the parameters of a recursive function as less as possible,more use static variables. * 3. If n = 5000, then O(n^2 logn) need atleast 4 sec to work * 4. dp[2][n] works faster than dp[n][2] * 5. if split wrt 1 char use '\\' before char: .split("\\."); * 6. while using dp, do not change the state variable for next recursive call apart from the function call itself. * 7. (int + int + long) can give integer overflow while (long + int + int) will not * * **/
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
1e8d7327c38c9e3a9250c45c691a6be4
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; public class D { static class Pair { int f; int s; // Pair() { } Pair(int f, int s) { this.f = f; this.s = s; } } static class Fast { BufferedReader br; StringTokenizer st; public Fast() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArray1(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (IOException e) { e.printStackTrace(); } return str; } } /* static long noOfDivisor(long a) { long count=0; long t=a; for(long i=1;i<=(int)Math.sqrt(a);i++) { if(a%i==0) count+=2; } if(a==((long)Math.sqrt(a)*(long)Math.sqrt(a))) { count--; } return count; }*/ static boolean isPrime(long a) { for (long i = 2; i <= (long) Math.sqrt(a); i++) { if (a % i == 0) return false; } return true; } static void primeFact(int n) { int temp = n; HashMap<Integer, Integer> h = new HashMap<>(); for (int i = 2; i * i <= n; i++) { if (temp % i == 0) { int c = 0; while (temp % i == 0) { c++; temp /= i; } h.put(i, c); } } if (temp != 1) h.put(temp, 1); } static void reverseArray(int a[]) { int n = a.length; for (int i = 0; i < n / 2; i++) { a[i] = a[i] ^ a[n - i - 1]; a[n - i - 1] = a[i] ^ a[n - i - 1]; a[i] = a[i] ^ a[n - i - 1]; } } static void f(int sx, int sy, int n, int m, int i, int j) { System.out.println(((sx + i - 2) % n + 1) + " " + ((sy - 2 + j) % m + 1)); } static void solve(int a, int b, int x, int y, int n) { if (n <= a - x) { a = a - n; System.out.println(a * b); // continue outer; } else { a = x; n = n - (a - x); if (n <= b - y) { b = b - n; System.out.println(a * b); // continue outer; } else { b = y; System.out.println(a * b); // continue outer; } } } static boolean pal(String s) { String s1 = ""; for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) return false; } return true; } static int max(int a, int b) { return a > b ? a : b; } static ArrayList<Integer> adj[]; static void build(int n) //do n+1 in actual parameter if index starts from 1 else n { adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i]=new ArrayList<>(); } static void addEdge(int s,int d) //v-1 || n-1 edges no need to change the actual parameters (use n only_) { adj[s].add(d); // adj[d].add(s); } static void dfs(int du[],int vis[],int i,int h) { vis[i]=1; for(int ne:adj[i]) { if(vis[ne]==0) dfs(du,vis,ne,h+1); } du[i]=h; } static int c=0; static int check1(int mid,int k,int vis[],int i,int par) { vis[i]=1;int f=0; if(adj[i].size()==0) { if (mid > 1||par==1) { return 1; } else { c++; return 0; } } for(int ne:adj[i]) { if(vis[ne]==0) { f=max(f, check1(mid,k,vis,ne,i)); } } f+=1; if(f>=mid&&par!=1&&i!=1) { c++; return 0; } return f; } public static void main(String args[]) throws IOException { Fast sc = new Fast(); PrintWriter out = new PrintWriter(System.out); int t1 = sc.nextInt(); outer: while (t1-- > 0) { int n = sc.nextInt();int k=sc.nextInt(); int p[]=new int[n+1]; for(int i=2;i<=n;i++) p[i]=sc.nextInt(); build(n+1); for(int i=2;i<=n;i++) { addEdge(p[i],i); } int du[]=new int[n+1]; int vis[]=new int[n+1]; dfs(du,vis,1,0); int maxh=0; for(int ne:du) maxh=max(maxh,ne); int l=1;int r=2*maxh+1;du[0]=1; while(l<=r) { int mid=(l+r)/2; Arrays.fill(vis,0); check1(mid,k,vis,1,0); if(c<=k) { r=mid-1; } else l=mid+1; c=0; } out.println(l); } out.close(); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
f61e3edd470055ad65cabc567da4a9b9
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; public class D { static class Pair { int f; int s; // Pair() { } Pair(int f, int s) { this.f = f; this.s = s; } } static class Fast { BufferedReader br; StringTokenizer st; public Fast() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArray1(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (IOException e) { e.printStackTrace(); } return str; } } /* static long noOfDivisor(long a) { long count=0; long t=a; for(long i=1;i<=(int)Math.sqrt(a);i++) { if(a%i==0) count+=2; } if(a==((long)Math.sqrt(a)*(long)Math.sqrt(a))) { count--; } return count; }*/ static boolean isPrime(long a) { for (long i = 2; i <= (long) Math.sqrt(a); i++) { if (a % i == 0) return false; } return true; } static void primeFact(int n) { int temp = n; HashMap<Integer, Integer> h = new HashMap<>(); for (int i = 2; i * i <= n; i++) { if (temp % i == 0) { int c = 0; while (temp % i == 0) { c++; temp /= i; } h.put(i, c); } } if (temp != 1) h.put(temp, 1); } static void reverseArray(int a[]) { int n = a.length; for (int i = 0; i < n / 2; i++) { a[i] = a[i] ^ a[n - i - 1]; a[n - i - 1] = a[i] ^ a[n - i - 1]; a[i] = a[i] ^ a[n - i - 1]; } } static void f(int sx, int sy, int n, int m, int i, int j) { System.out.println(((sx + i - 2) % n + 1) + " " + ((sy - 2 + j) % m + 1)); } static void solve(int a, int b, int x, int y, int n) { if (n <= a - x) { a = a - n; System.out.println(a * b); // continue outer; } else { a = x; n = n - (a - x); if (n <= b - y) { b = b - n; System.out.println(a * b); // continue outer; } else { b = y; System.out.println(a * b); // continue outer; } } } static boolean pal(String s) { String s1 = ""; for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) return false; } return true; } static int max(int a, int b) { return a > b ? a : b; } static ArrayList<Integer> adj[]; static void build(int n) //do n+1 in actual parameter if index starts from 1 else n { adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i]=new ArrayList<>(); } static void addEdge(int s,int d) //v-1 || n-1 edges no need to change the actual parameters (use n only_) { adj[s].add(d); // adj[d].add(s); } static void dfs(int du[],int vis[],int i,int h) { vis[i]=1; for(int ne:adj[i]) { if(vis[ne]==0) dfs(du,vis,ne,h+1); } du[i]=h; } static int dfs1(int dd[],int vis[],int i,int h) { vis[i]=1;int f=0; if(adj[i].size()==0) return dd[i]=0; for(int ne:adj[i]) { if(vis[ne]==0) f=max(f, dfs1(dd,vis,ne,h)); } return dd[i]=1+f; } static int check(int mid,int k,int du[],int vis[],int i,int pre) { vis[i]=1;int f=0; for(int ne:adj[i]) { if(vis[ne]==0) { if(du[ne]-du[pre]+1<=mid) f+=check(mid,k,du,vis,ne,pre); else if(du[ne]-du[pre]+1>mid) f+=1+check(mid,k,du,vis,ne,ne); } } return f; } static int c=0; static int check1(int mid,int k,int vis[],int i,int par) { vis[i]=1;int f=0; if(adj[i].size()==0) { if (mid > 1||par==1) { //if(mid==4) // System.out.println(i + "=" + 1); return 1; } else { c++; // if(mid==4) // System.out.println(i + "=" + 0); return 0; } } for(int ne:adj[i]) { if(vis[ne]==0) { f=max(f, check1(mid,k,vis,ne,i)); } } f+=1; if(f>=mid&&par!=1&&i!=1) { // if(mid==4) // System.out.println(i+"="+f); c++; // System.out.println(i+"="+f); return 0; } //if(mid==4) // System.out.println(i+"="+f); return f; } public static void main(String args[]) throws IOException { Fast sc = new Fast(); PrintWriter out = new PrintWriter(System.out); int t1 = sc.nextInt(); outer: while (t1-- > 0) { int n = sc.nextInt();int k=sc.nextInt(); int p[]=new int[n+1]; for(int i=2;i<=n;i++) p[i]=sc.nextInt(); build(n+1); for(int i=2;i<=n;i++) { addEdge(p[i],i); } int du[]=new int[n+1];int dd[]=new int[n+1]; int vis[]=new int[n+1]; dfs(du,vis,1,0); dfs1(dd,vis,1,0); int maxh=0; for(int ne:du) maxh=max(maxh,ne); /* for(int i=1;i<=n;i++) out.print(du[i]+" "); out.println();*/ int l=1;int r=2*maxh+1;du[0]=1; // out.println(r); while(l<=r) { int mid=(l+r)/2; Arrays.fill(vis,0); check1(mid,k,vis,1,0); // out.println(c+" "+mid); if(c<=k) { r=mid-1; } else l=mid+1; c=0; } out.println(l); } out.close(); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
c0f8a228a64cb500f36783367a4c80ca
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; public class Main { static Scanner sc; static PrintWriter pw; static int depth[][], par[]; static boolean[] vis; static void dfs(int u) { vis[u] = true; if (u == 0) return; if (vis[par[u]]) { depth[u][0] = 1 + depth[par[u]][0]; depth[u][1] = u; return; } dfs(par[u]); depth[u][0] = 1 + depth[par[u]][0]; depth[u][1] = u; } public static void main(String[] args) throws Exception { pw = new PrintWriter(System.out); sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(), k = sc.nextInt(); par = new int[n + 1]; depth = new int[n + 1][2]; vis = new boolean[n + 1]; for (int i = 2; i <= n; i++) par[i] = sc.nextInt(); for (int i = n; i >= 0; i--) { if (!vis[i]) dfs(i); } Arrays.sort(depth, (a, b) -> a[0] - b[0]); int l = 1, r = n - 1; while (l <= r) { int mid = l + r >> 1; boolean[] vis = new boolean[n + 1]; int[] cnt = new int[n + 1]; for (int i = n; i > 1; i--) { if (!vis[depth[i][1]]) { int c = 0, j = depth[i][1]; while (j != 0 && c < mid) { if (vis[j]) break; vis[j] = true; c++; j = par[j]; } if (c == mid && j != 1 && j != 0) cnt[i]++; } cnt[par[i]] += cnt[i]; } // System.out.println(Arrays.toString(cnt) + " " + mid); if (cnt[1] <= k) { r = mid - 1; } else { l = mid + 1; } } pw.println(l); } pw.flush(); } 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 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 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
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
53590caae8e3e228a1c01aa5852cee37
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class ResetKEdges { private static final int START_TEST_CASE = 1; public static void solveCase(FastIO io, int testCase) { final int N = io.nextInt(); final int K = io.nextInt(); Node[] nodes = new Node[N + 1]; for (int i = 1; i <= N; ++i) { nodes[i] = new Node(i); } for (int i = 2; i <= N; ++i) { final int P = io.nextInt(); nodes[P].next.add(nodes[i]); nodes[i].parent = nodes[P]; } nodes[1].initDepth(0); int ans = BinarySearch.firstThat(1, N + 1, new BinarySearch.IntCheck() { @Override public boolean valid(int targetDepth) { int cuts = cutsRequired(nodes, targetDepth); return cuts <= K; } }); io.println(ans); } private static int cutsRequired(Node[] nodes, int targetDepth) { final int N = nodes.length - 1; AscendingDiscretePriorityQueue<Node> pq = new AscendingDiscretePriorityQueue<>( new AscendingDiscretePriorityQueue.IntConverter<Node>() { @Override public int toInt(Node u) { return N - u.depth; } } ); int[] indegRem = new int[N + 1]; for (int i = 1; i <= N; ++i) { if (nodes[i].next.isEmpty()) { pq.offer(nodes[i]); } indegRem[i] = nodes[i].next.size(); } boolean[] isCut = new boolean[N + 1]; int cuts = 0; while (!pq.isEmpty()) { Node u = pq.poll(); if (u.depth <= targetDepth) { break; } if (isCut[u.id]) { continue; } Node p = u; for (int i = 1; i < targetDepth; ++i) { p = p.parent; if (isCut[p.id]) { p = null; break; } } if (p == null) { continue; } isCut[p.id] = true; ++cuts; --indegRem[p.parent.id]; if (indegRem[p.parent.id] == 0) { pq.offer(p.parent); } } return cuts; } private static class Node { public int id; public ArrayList<Node> next = new ArrayList<>(); public Node parent; public Node(int id) { this.id = id; } public int depth; public void initDepth(int d) { depth = d; for (Node v : next) { v.initDepth(d + 1); } } } /** * This is an priority queue containing int values in descending order. * - All operations run in amortized O(1) time. * - However, it can only offer values that are less-than-or-equal-to the last value of poll(). * - Before the first poll() call, any values can be inserted up to the maximum size initialized of the priority queue. */ public static class AscendingDiscretePriorityQueue<T> { private int idx; private ArrayList<ArrayDeque<T>> queues; private IntConverter<T> converter; public AscendingDiscretePriorityQueue(IntConverter<T> converter) { this.queues = new ArrayList<>(); this.converter = converter; } public boolean offer(T item) { int x = converter.toInt(item); if (x < idx) { return false; } getOrCreate(x).offer(item); return true; } public T peek() { return nextQueue().peek(); } public T poll() { return nextQueue().poll(); } public boolean isEmpty() { return nextQueue() == null; } private ArrayDeque<T> nextQueue() { while (idx < queues.size()) { ArrayDeque<T> q = queues.get(idx); if (q != null && !q.isEmpty()) { return q; } ++idx; } return null; } private ArrayDeque<T> getOrCreate(int i) { while (queues.size() <= i) { queues.add(null); } ArrayDeque<T> q = queues.get(i); if (q == null) { q = new ArrayDeque<>(); queues.set(i, q); } return q; } public static interface IntConverter<T> { public int toInt(T item); } } /** * Generic binary search to find the first or last value resulting in a matching condition. */ // EXAMPLE USAGE (find insertion index in sorted array `A`): /* int insertionIndex = BinarySearch.firstThat(0, A.length, new BinarySearch.IntCheck() { @Override public boolean valid(int index) { return A[index] > mid; } }); */ public static class BinarySearch { // Finds the left-most value that satisfies the IntCheck in the range [L, R). // It will return R if the nothing in the range satisfies the check. public static int firstThat(int L, int R, IntCheck check) { while (L < R) { int M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static int lastThat(int L, int R, IntCheck check) { int firstValue = firstThat(L, R, new IntCheck() { @Override public boolean valid(int value) { return !check.valid(value); } }); return firstValue - 1; } // Finds the left-most value that satisfies the LongCheck in the range [L, R). public static long firstThat(long L, long R, LongCheck check) { while (L < R) { long M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static long lastThat(long L, long R, LongCheck check) { long firstValue = firstThat(L, R, new LongCheck() { @Override public boolean valid(long value) { return !check.valid(value); } }); return firstValue - 1; } public static interface LongCheck { public boolean valid(long value); } public static interface IntCheck { public boolean valid(int value); } } public static void solve(FastIO io) { final int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, START_TEST_CASE + t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
13c7da90cdf725651b647ff1020b6233
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class ResetKEdges { private static final int START_TEST_CASE = 1; public static void solveCase(FastIO io, int testCase) { final int N = io.nextInt(); final int K = io.nextInt(); Node[] nodes = new Node[N + 1]; for (int i = 1; i <= N; ++i) { nodes[i] = new Node(i); } for (int i = 2; i <= N; ++i) { final int P = io.nextInt(); nodes[P].next.add(nodes[i]); nodes[i].parent = nodes[P]; } nodes[1].initDepth(0); int ans = BinarySearch.firstThat(1, N + 1, new BinarySearch.IntCheck() { @Override public boolean valid(int targetDepth) { int cuts = cutsRequired(nodes, targetDepth); // System.out.format("targetDepth = %d, cuts = %d\n", targetDepth, cuts); return cuts <= K; } }); io.println(ans); // int ans = BinarySearch.firstThat(1, N + 1, new BinarySearch.IntCheck() { // @Override // public boolean valid(int targetDepth) { // int[] outPtr = {0}; // cutsRequired(nodes[1], 0, targetDepth, outPtr); // return outPtr[0] <= K; // } // }); // io.println(ans); } private static void cutsRequired(Node u, int currDepth, int targetDepth, int[] outPtr) { if (currDepth > targetDepth) { ++outPtr[0]; currDepth = 1; } for (Node v : u.next) { cutsRequired(v, currDepth + 1, targetDepth, outPtr); } } private static int cutsRequired(Node[] nodes, int targetDepth) { final int N = nodes.length - 1; AscendingDiscretePriorityQueue<Node> pq = new AscendingDiscretePriorityQueue<>( new AscendingDiscretePriorityQueue.IntConverter<Node>() { @Override public int toInt(Node u) { return N - u.depth; } } ); int[] indegRem = new int[N + 1]; for (int i = 1; i <= N; ++i) { if (nodes[i].next.isEmpty()) { pq.offer(nodes[i]); } indegRem[i] = nodes[i].next.size(); } boolean[] isCut = new boolean[N + 1]; int cuts = 0; while (!pq.isEmpty()) { Node u = pq.poll(); if (u.depth <= targetDepth) { break; } if (isCut[u.id]) { continue; } Node p = u; for (int i = 1; i < targetDepth; ++i) { p = p.parent; if (isCut[p.id]) { p = null; break; } } // System.out.format("[target = %d] u = %d, p = %s\n", targetDepth, u.id, p == null ? "NULL" : p.id); if (p == null) { continue; } isCut[p.id] = true; ++cuts; --indegRem[p.parent.id]; if (indegRem[p.parent.id] == 0) { pq.offer(p.parent); } } return cuts; } private static class Node { public int id; public ArrayList<Node> next = new ArrayList<>(); public Node parent; public Node(int id) { this.id = id; } public int depth; public void initDepth(int d) { depth = d; for (Node v : next) { v.initDepth(d + 1); } } private static final Comparator<Node> BY_DEPTH = new Comparator<Node>() { @Override public int compare(Node a, Node b) { return Integer.compare(a.depth, b.depth); } }; } /** * This is an priority queue containing int values in descending order. * - All operations run in amortized O(1) time. * - However, it can only offer values that are less-than-or-equal-to the last value of poll(). * - Before the first poll() call, any values can be inserted up to the maximum size initialized of the priority queue. */ public static class AscendingDiscretePriorityQueue<T> { private int idx; private ArrayList<ArrayDeque<T>> queues; private IntConverter<T> converter; public AscendingDiscretePriorityQueue(IntConverter<T> converter) { this.queues = new ArrayList<>(); this.converter = converter; } public boolean offer(T item) { int x = converter.toInt(item); if (x < idx) { return false; } getOrCreate(x).offer(item); return true; } public T peek() { return nextQueue().peek(); } public T poll() { return nextQueue().poll(); } public boolean isEmpty() { return nextQueue() == null; } private ArrayDeque<T> nextQueue() { while (idx < queues.size()) { ArrayDeque<T> q = queues.get(idx); if (q != null && !q.isEmpty()) { return q; } ++idx; } return null; } private ArrayDeque<T> getOrCreate(int i) { while (queues.size() <= i) { queues.add(null); } ArrayDeque<T> q = queues.get(i); if (q == null) { q = new ArrayDeque<>(); queues.set(i, q); } return q; } public static interface IntConverter<T> { public int toInt(T item); } } /** * Generic binary search to find the first or last value resulting in a matching condition. */ // EXAMPLE USAGE (find insertion index in sorted array `A`): /* int insertionIndex = BinarySearch.firstThat(0, A.length, new BinarySearch.IntCheck() { @Override public boolean valid(int index) { return A[index] > mid; } }); */ public static class BinarySearch { // Finds the left-most value that satisfies the IntCheck in the range [L, R). // It will return R if the nothing in the range satisfies the check. public static int firstThat(int L, int R, IntCheck check) { while (L < R) { int M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static int lastThat(int L, int R, IntCheck check) { int firstValue = firstThat(L, R, new IntCheck() { @Override public boolean valid(int value) { return !check.valid(value); } }); return firstValue - 1; } // Finds the left-most value that satisfies the LongCheck in the range [L, R). public static long firstThat(long L, long R, LongCheck check) { while (L < R) { long M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static long lastThat(long L, long R, LongCheck check) { long firstValue = firstThat(L, R, new LongCheck() { @Override public boolean valid(long value) { return !check.valid(value); } }); return firstValue - 1; } public static interface LongCheck { public boolean valid(long value); } public static interface IntCheck { public boolean valid(int value); } } public static void solve(FastIO io) { final int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, START_TEST_CASE + t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
4b3d59a5d9b776ab20e74829ec9f949b
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class ResetKEdges { private static final int START_TEST_CASE = 1; public static void solveCase(FastIO io, int testCase) { final int N = io.nextInt(); final int K = io.nextInt(); Node[] nodes = new Node[N + 1]; for (int i = 1; i <= N; ++i) { nodes[i] = new Node(i); } for (int i = 2; i <= N; ++i) { final int P = io.nextInt(); nodes[P].next.add(nodes[i]); nodes[i].parent = nodes[P]; } nodes[1].initDepth(0); int ans = BinarySearch.firstThat(1, N + 1, new BinarySearch.IntCheck() { @Override public boolean valid(int targetDepth) { int cuts = cutsRequired(nodes, targetDepth); // System.out.format("targetDepth = %d, cuts = %d\n", targetDepth, cuts); return cuts <= K; } }); io.println(ans); // int ans = BinarySearch.firstThat(1, N + 1, new BinarySearch.IntCheck() { // @Override // public boolean valid(int targetDepth) { // int[] outPtr = {0}; // cutsRequired(nodes[1], 0, targetDepth, outPtr); // return outPtr[0] <= K; // } // }); // io.println(ans); } private static void cutsRequired(Node u, int currDepth, int targetDepth, int[] outPtr) { if (currDepth > targetDepth) { ++outPtr[0]; currDepth = 1; } for (Node v : u.next) { cutsRequired(v, currDepth + 1, targetDepth, outPtr); } } private static int cutsRequired(Node[] nodes, int targetDepth) { final int N = nodes.length - 1; PriorityQueue<Node> pq = new PriorityQueue<>(Collections.reverseOrder(Node.BY_DEPTH)); int[] indegRem = new int[N + 1]; for (int i = 1; i <= N; ++i) { if (nodes[i].next.isEmpty()) { pq.offer(nodes[i]); } indegRem[i] = nodes[i].next.size(); } boolean[] isCut = new boolean[N + 1]; int cuts = 0; while (!pq.isEmpty()) { Node u = pq.poll(); if (u.depth <= targetDepth) { break; } if (isCut[u.id]) { continue; } Node p = u; for (int i = 1; i < targetDepth; ++i) { p = p.parent; if (isCut[p.id]) { p = null; break; } } // System.out.format("[target = %d] u = %d, p = %s\n", targetDepth, u.id, p == null ? "NULL" : p.id); if (p == null) { continue; } isCut[p.id] = true; ++cuts; --indegRem[p.parent.id]; if (indegRem[p.parent.id] == 0) { pq.offer(p.parent); } } return cuts; } private static class Node { public int id; public ArrayList<Node> next = new ArrayList<>(); public Node parent; public Node(int id) { this.id = id; } public int depth; public void initDepth(int d) { depth = d; for (Node v : next) { v.initDepth(d + 1); } } private static final Comparator<Node> BY_DEPTH = new Comparator<Node>() { @Override public int compare(Node a, Node b) { return Integer.compare(a.depth, b.depth); } }; } /** * Generic binary search to find the first or last value resulting in a matching condition. */ // EXAMPLE USAGE (find insertion index in sorted array `A`): /* int insertionIndex = BinarySearch.firstThat(0, A.length, new BinarySearch.IntCheck() { @Override public boolean valid(int index) { return A[index] > mid; } }); */ public static class BinarySearch { // Finds the left-most value that satisfies the IntCheck in the range [L, R). // It will return R if the nothing in the range satisfies the check. public static int firstThat(int L, int R, IntCheck check) { while (L < R) { int M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static int lastThat(int L, int R, IntCheck check) { int firstValue = firstThat(L, R, new IntCheck() { @Override public boolean valid(int value) { return !check.valid(value); } }); return firstValue - 1; } // Finds the left-most value that satisfies the LongCheck in the range [L, R). public static long firstThat(long L, long R, LongCheck check) { while (L < R) { long M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static long lastThat(long L, long R, LongCheck check) { long firstValue = firstThat(L, R, new LongCheck() { @Override public boolean valid(long value) { return !check.valid(value); } }); return firstValue - 1; } public static interface LongCheck { public boolean valid(long value); } public static interface IntCheck { public boolean valid(int value); } } public static void solve(FastIO io) { final int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, START_TEST_CASE + t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
0fbaafdfa915ffc907385ab31d72157c
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class Main { static Main2 admin = new Main2(); public static void main(String[] args) { admin.start(); } } class Main2 { //---------------------------------INPUT READER-----------------------------------------// public BufferedReader br; StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine());} catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long n) {int[]ret=new int[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} long[] nal(long n) {long[]ret=new long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} Integer[] nA(long n) {Integer[]ret=new Integer[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} Long[] nAl(long n) {Long[]ret=new Long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} //--------------------------------------PRINTER------------------------------------------// PrintWriter w; void p(int i) {w.println(i);} void p(long l) {w.println(l);} void p(double d) {w.println(d);} void p(String s) { w.println(s);} void pr(int i) {w.print(i);} void pr(long l) {w.print(l);} void pr(double d) {w.print(d);} void pr(String s) { w.print(s);} void pl() {w.println();} //--------------------------------------VARIABLES-----------------------------------------// long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; long mod = 1000000007; { w = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); } //----------------------START---------------------// void start() { int t = ni(); while(t-- > 0) solve(); w.close(); } int n, k; List<List<Integer>> graph; int used = 0; int[] lvls; int[] pt; int dfs (int at, int ht) { int max = imi; for(int i: graph.get(at)) { max = Math.max(max, dfs(i, ht)); } if(max == imi) max = 0; if(max == ht - 1 && pt[at] != 0) { used++; return imi; } return max + 1; } boolean check(int ht) { used = 0; dfs(0, ht); return used <= k; } void solve() { n = ni(); k = ni(); graph = new ArrayList<>(); lvls = new int[n]; pt = new int[n]; for(int i = 0; i < n; i++) graph.add(new ArrayList<>()); for(int i = 1; i < n; i++) { int pts = ni() - 1; graph.get(pts).add(i); pt[i] = pts; } int l = 0; // false int r = n; // true dfsLvl(0); while(l < r - 1) { int mid = (l + r) / 2; if(check(mid)) r = mid; else l = mid; } p(r); } int dfsLvl (int at) { int max = imi; for(int i: graph.get(at)) { max = Math.max(max, dfsLvl(i)); } if(max == imi) lvls[at] = 0; else lvls[at] = max; return lvls[at] + 1; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
8eb37e9e1c3ae26c5168d0b6a1fad63c
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
/* Goal: Become better in CP! Key: Consistency and Discipline Desire: SDE @ Google USA Motto: Do what i Love <=> Love what i do If you don't use your brain 100%, it deteriorates gradually */ import java.util.*; import java.io.*; import java.math.*; public class B1 { static StringBuffer str=new StringBuffer(); static BufferedReader bf; static PrintWriter pw; static int n, k; static List<List<Integer>> l; static int op=0; static int dfs(int u, int p, int x){ int depth=0; for(int v:l.get(u)){ if(v!=p){ depth=Math.max(depth, dfs(v, u, x)+1); } } if(depth==x-1 && p!=1 && u!=1){ // System.out.println(u+"*"+x); op++; return -1; } return depth; } static boolean isPos(int x){ op=0; dfs(1, -1, x); // System.out.println(x+" "+op); return op<=k; } static void solve(int te) throws Exception{ int l=0, r=n; while(r-l>1){ int mid=l+(r-l)/2; if(isPos(mid)) r=mid; else l=mid; } str.append(r).append("\n"); } public static void main(String[] args) throws java.lang.Exception { 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 q1 = Integer.parseInt(bf.readLine().trim()); for(int te=1;te<=q1;te++) { String s[]=bf.readLine().trim().split("\\s+"); n=Integer.parseInt(s[0]); k=Integer.parseInt(s[1]); s=bf.readLine().trim().split("\\s+"); l=new ArrayList<>(); for(int i=0;i<=n;i++) l.add(new ArrayList<>()); for(int i=0;i<n-1;i++){ int u=Integer.parseInt(s[i]); l.get(u).add(i+2); l.get(i+2).add(u); } solve(te); } pw.print(str); pw.flush(); // System.out.println(str); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
1e7c013e3af69ff444a40124f4f9bea1
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; /** * Author : joney_000[developer.jaswant@gmail.com] * Algorithm : Default Template * Platform : Codeforces * Ref : N/A */ public class A{ private InputStream inputStream ; private OutputStream outputStream ; private FastReader in ; private PrintWriter out ; private final int BUFFER = 100005; private final long mod = 1000000000+7; private final int INF = Integer.MAX_VALUE; private final long INF_L = Long.MAX_VALUE / 10; public A(){} public A(boolean stdIO)throws FileNotFoundException{ // stdIO = false; if(stdIO){ inputStream = System.in; outputStream = System.out; }else{ inputStream = new FileInputStream("input.txt"); outputStream = new FileOutputStream("output.txt"); } in = new FastReader(inputStream); out = new PrintWriter(outputStream); } void run()throws Exception{ int tests = i(); for(int testId = 1; testId <= tests; testId++){ int n = i(); int k = i(); LinkedList<Integer> graph[] = new LinkedList[n + 1]; for(int node = 1; node <= n; node++){ graph[node] = new LinkedList<Integer>(); } for(int i = 2; i <= n; i++){ int u = i; int v = i(); graph[u].add(v); graph[v].add(u); } if(k == n - 1){ out.write("1\n"); continue; } int ans = 0; int low = 1; int high = n - 1; while(low <= high){ int mid = low + (high - low)/2; if(isGraphOfMaxHieghtPossible(mid, graph, k, 1, n)){ ans = mid; high = mid - 1; }else{ low = mid + 1; } } out.write(""+ans+"\n"); } } final int MAXN = (int)2e5 + 1; boolean vis[] = new boolean[MAXN]; int distanceFromLeaf[] = new int[MAXN]; int parent[] = new int[MAXN]; boolean isGraphOfMaxHieghtPossible(int depth, LinkedList<Integer> graph[], int operations, int root, int n){ LinkedList<Integer> stack = new LinkedList<>(); stack.add(1); Arrays.fill(vis, 1 , n + 1, false); Arrays.fill(distanceFromLeaf, 1, n + 1, 0); vis[root] = true; while(!stack.isEmpty()){ int u = stack.getLast(); boolean hasChildren = false; for(int v: graph[u]){ if(!vis[v]){ parent[v] = u; stack.add(v); vis[v] = true; hasChildren = true; break; } } if(!hasChildren){ stack.removeLast(); int maxDepth = 0; for(int v: graph[u]){ if(v == parent[u]) continue; maxDepth = Math.max(1 + distanceFromLeaf[v], maxDepth); } distanceFromLeaf[u] = maxDepth; // out.write("max_dis("+u+") = "+distanceFromLeaf[u]+" d = "+depth+"\n"); if(distanceFromLeaf[u] >= depth - 1){ if(u == root || parent[u] == root){ // } else if(operations > 0){ distanceFromLeaf[u] = -1; operations--; }else { return false; } } } } return true; } long gcd(long a, long b){ if(b == 0)return a; return gcd(b, a % b); } long lcm(long a, long b){ if(a == 0 || b == 0)return 0; return (a * b)/gcd(a, b); } long mulMod(long a, long b, long mod){ if(a == 0 || b == 0)return 0; if(b == 1)return a; long ans = mulMod(a, b/2, mod); ans = (ans * 2) % mod; if(b % 2 == 1)ans = (a + ans)% mod; return ans; } long pow(long a, long b, long mod){ if(b == 0)return 1; if(b == 1)return a; long ans = pow(a, b/2, mod); ans = mulMod(ans, ans, mod); if(ans >= mod)ans %= mod; if(b % 2 == 1)ans = mulMod(a, ans, mod); if(ans >= mod)ans %= mod; return ans; } // 20*20 nCr Pascal Table long[][] ncrTable(){ long ncr[][] = new long[21][21]; for(int i = 0; i <= 20; i++){ ncr[i][0] = ncr[i][i] = 1L; } for(int j = 0; j <= 20; j++){ for(int i = j + 1; i <= 20; i++){ ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; } } return ncr; } int i()throws Exception{ return in.nextInt(); } long l()throws Exception{ return in.nextLong(); } double d()throws Exception{ return in.nextDouble(); } char c()throws Exception{ return in.nextCharacter(); } String s()throws Exception{ return in.nextLine(); } BigInteger bi()throws Exception{ return in.nextBigInteger(); } private void closeResources(){ out.flush(); out.close(); return; } // IMP: roundoff upto 2 digits // double roundOff = Math.round(a * 100.0) / 100.0; // or // System.out.printf("%.2f", val); // print upto 2 digits after decimal // val = ((long)(val * 100.0))/100.0; public static void main(String[] args) throws java.lang.Exception{ A driver = new A(true); driver.run(); driver.closeResources(); } } class FastReader{ private boolean finished = false; private InputStream stream; private byte[] buf = new byte[4 * 1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream){ this.stream = stream; } public int read(){ if (numChars == -1){ throw new InputMismatchException (); } if (curChar >= numChars){ curChar = 0; try{ numChars = stream.read (buf); } catch (IOException e){ throw new InputMismatchException (); } if (numChars <= 0){ return -1; } } return buf[curChar++]; } public int peek(){ if (numChars == -1){ return -1; } if (curChar >= numChars){ curChar = 0; try{ numChars = stream.read (buf); } catch (IOException e){ return -1; } if (numChars <= 0){ return -1; } } return buf[curChar]; } public int nextInt(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } int res = 0; do{ if(c==','){ c = read(); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } 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{ if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public String nextString(){ int c = read (); while (isSpaceChar (c)) c = read (); StringBuilder res = new StringBuilder (); do{ res.appendCodePoint (c); c = read (); } while (!isSpaceChar (c)); return res.toString (); } public boolean isSpaceChar(int c){ if (filter != null){ return filter.isSpaceChar (c); } return isWhitespace (c); } public static boolean isWhitespace(int c){ return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0(){ StringBuilder buf = new StringBuilder (); int c = read (); while (c != '\n' && c != -1){ if (c != '\r'){ buf.appendCodePoint (c); } c = read (); } return buf.toString (); } public String nextLine(){ String s = readLine0 (); while (s.trim ().length () == 0) s = readLine0 (); return s; } public String nextLine(boolean ignoreEmptyLines){ if (ignoreEmptyLines){ return nextLine (); }else{ return readLine0 (); } } public BigInteger nextBigInteger(){ try{ return new BigInteger (nextString ()); } catch (NumberFormatException e){ throw new InputMismatchException (); } } public char nextCharacter(){ int c = read (); while (isSpaceChar (c)) c = read (); return (char) c; } public double nextDouble(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } double res = 0; while (!isSpaceChar (c) && c != '.'){ if (c == 'e' || c == 'E'){ return res * Math.pow (10, nextInt ()); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } if (c == '.'){ c = read (); double m = 1; while (!isSpaceChar (c)){ if (c == 'e' || c == 'E'){ return res * Math.pow (10, nextInt ()); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } m /= 10; res += (c - '0') * m; c = read (); } } return res * sgn; } public boolean isExhausted(){ int value; while (isSpaceChar (value = peek ()) && value != -1) read (); return value == -1; } public String next(){ return nextString (); } public SpaceCharFilter getFilter(){ return filter; } public void setFilter(SpaceCharFilter filter){ this.filter = filter; } public interface SpaceCharFilter{ public boolean isSpaceChar(int ch); } } class Pair implements Comparable<Pair>{ public int a; public int b; public Pair(){ this.a = 0; this.b = 0; } public Pair(int a,int b){ this.a = a; this.b = b; } public int compareTo(Pair p){ if(this.a == p.a){ return this.b - p.b; } return this.a - p.a; } @Override public String toString(){ return "a = " + this.a + " b = " + this.b; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
5c3549fd312dc378dd0e6c971562347e
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class Main { private static void solve(int n, int k, Map<Integer, List<Integer>> g){ int start = 1, end = n - 1; while(start + 1 < end){ int mid = start + (end - start) / 2; if(isValid(mid, k, g)){ end = mid; } else { start = mid; } } if(isValid(start, k, g)){ out.println(start); return; } out.println(end); } private static boolean isValid(int h, int k, Map<Integer, List<Integer>> g){ int[] cost = new int[1]; dfs(1, -1, h, g, cost); return cost[0] <= k; } private static int dfs(int i, int prev, int h, Map<Integer, List<Integer>> g, int[] cost){ int maxH = 0; for(int child: g.get(i)){ maxH = Math.max(maxH, 1 + dfs(child, i, h, g, cost)); } if(prev != 1 && i != 1 && maxH == h - 1){ cost[0]++; return -1; } return maxH; } public static void main(String[] args){ MyScanner scanner = new MyScanner(); int testCount = scanner.nextInt(); for(int testIdx = 1; testIdx <= testCount; testIdx++){ int n = scanner.nextInt(); int k = scanner.nextInt(); Map<Integer, List<Integer>> g = new HashMap<>(); for(int i = 1; i <= n; i++){ g.put(i, new ArrayList<>()); } for(int i = 2; i <= n; i++){ int parent = scanner.nextInt(); if(i != parent) { g.get(parent).add(i); } } solve(n, k, g); } out.close(); } static void print1DArray(int[] arr){ for(int i = 0; i < arr.length; i++){ out.print(arr[i]); if(i < arr.length - 1){ out.print(' '); } } out.print('\n'); } static void print1DArrayList(List<Integer> arrayList){ for(int i = 0; i < arrayList.size(); i++){ out.print(arrayList.get(i)); if(i < arrayList.size() - 1){ out.print(' '); } } out.print('\n'); } public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
8bced60e1d294094eeafec9085ec380b
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
// package faltu; import java.util.*; import java.util.Map.Entry; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; public class Main { // ***********************MATHS--STARTS************************************************* // private static ArrayList<Long> get_divisor(long x) { ArrayList<Long>a=new ArrayList<Long>(); for(long i=2;i*i<=x;i++) { if(x%i==0) { a.add((long) i); if(x/i!=i)a.add(x/i); } } return a; } private static int CntOfFactor(long x) { ArrayList<Long>a=new ArrayList<Long>(); for(long i=1;i*i<=x;i++) { if(x%i==0) { a.add((long) i); if(x/i!=i)a.add(x/i); } } return a.size(); } static long[] sieve; static long[] smallestPrime; public static void sieve() { int n=4000000+1; sieve=new long[n]; smallestPrime=new long[n]; sieve[0]=1; sieve[1]=1; for(int i=2;i<n;i++){ sieve[i]=i; smallestPrime[i]=i; } for(int i=2;i*i<n;i++){ if(sieve[i]==i){ for(int j=i*i;j<n;j+=i){ if(sieve[j]==j)sieve[j]=1; if(smallestPrime[j]==j||smallestPrime[j]>i)smallestPrime[j]=i; } } } } static long nCr(long n,long r,long MOD) { computeFact(n, MOD); if(n<r)return 0; if(r==0)return 1; return fact[(int) n]*mod_inv(fact[(int) r],MOD)%MOD*mod_inv(fact[(int) (n-r)],MOD)%MOD; } static long[]fact; static void computeFact(long n,long MOD) { fact=new long[(int)n+1]; fact[0]=1; for(int i=1;i<=n;i++)fact[i]=(fact[i-1]*i%MOD)%MOD; } static long bin_expo(long a,long b,long MOD) { if(b == 0)return 1; long ans = bin_expo(a,b/2,MOD); ans = (ans*ans)%MOD; if(b % 2!=0){ ans = (ans*a)%MOD; } return ans%MOD; } static int ceil(int x, int y) {return (x % y == 0 ? x / y : (x / y + 1));} static long ceil(long x, long y) {return (x % y == 0 ? x / y : (x / y + 1));} static long mod_add(long a, long b, long m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} static long mod_mul(long a, long b, long m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} static long mod_sub(long a, long b, long m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} static long mod_inv(long n,long p) {return bin_expo(n,p-2,p);} static long gcd(long a, long b){if (a == 0) {return b;}return gcd(b % a, a); } static int gcd(int a, int b){if (a == 0) {return b; }return gcd(b % a, a); } static long lcm(long a,long b){return (a / gcd(a, b)) * b;} static long min(long x,long y) {return Math.min(x, y);}static long max(long x,long y) {return Math.max(x, y);} static int min(int x,int y) {return Math.min(x, y);}static int max(int x,int y) {return Math.max(x, y);} static ArrayList<String>powof2s; static void powof2S() { long i=1; while(i<(long)2e18) { powof2s.add(String.valueOf(i)); i*=2; } } static long power(long a, long b){ a %=MOD;long out = 1; while (b > 0) { if((b&1)!=0)out = out * a % MOD; a = a * a % MOD; b >>= 1; a*=a; } return out; } static boolean coprime(int a, long l){return (gcd(a, l) == 1);} // ****************************MATHS-ENDS***************************************************** // ***********************BINARY-SEARCH STARTS*********************************************** public static int upperBound(long[] arr, long m, int l, int r) { while(l<=r) { int mid=(l+r)/2; if(arr[mid]<=m) l=mid+1; else r=mid-1; } return l; } public static int lowerBound(long[] a, long m, int l, int r) { while(l<=r) { int mid=(l+r)/2; if(a[mid]<m) l=mid+1; else r=mid-1; } return l; } public static int lowerBound(ArrayList<Integer> ar,int k){ int s=0,e=ar.size(); while (s!=e){ int mid = s+e>>1; if (ar.get(mid) <k)s=mid+1; else e=mid; } if(s==ar.size())return -1; return s; } public static int upperBound(ArrayList<Integer> ar,int k){ int s=0,e=ar.size(); while (s!=e){ int mid = s+e>>1; if (ar.get(mid) <=k)s=mid+1; else e=mid; } if(s==ar.size())return -1; return s; } public static long getClosest(long val1, long val2,long target){if (target - val1 >= val2 - target)return val2; else return val1;} static void ruffleSort(long[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { long oi=r.nextInt(n), temp=a[i]; a[i]=a[(int)oi]; a[(int)oi]=temp; } Arrays.sort(a); } static void ruffleSort(int[] a){ int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } int ceilIndex(int input[], int T[], int end, int s){ int start = 0; int middle; int len = end; while(start <= end){ middle = (start + end)/2; if(middle < len && input[T[middle]] < s && s <= input[T[middle+1]]){ return middle+1; }else if(input[T[middle]] < s){ start = middle+1; }else{ end = middle-1; } } return -1; } static int lowerLimitBinarySearch(ArrayList<Long> v,long k) { int n =v.size(); int first = 0,second = n; while(first <second) { int mid = first + (second-first)/2; if(v.get(mid) > k) { second = mid; }else { first = mid+1; } } if(first < n && v.get(first) < k) { first++; } return first; //1 index } public static int searchindex(long arr[], long t){int index = Arrays.binarySearch(arr, t);return (index < 0) ? -1 : index;} public static long[] sort(long[] a) {ArrayList<Long> al = new ArrayList<>();for(int i=0;i<a.length;i++) al.add(a[i]);Collections.sort(al);for(int i=0;i<a.length;i++) a[i]=al.get(i);return a;} public static int[] sort(int[] a) {ArrayList<Integer> al = new ArrayList<>();for(int i=0;i<a.length;i++) al.add(a[i]);Collections.sort(al);for(int i=0;i<a.length;i++) a[i]=al.get(i);return a;} // *******************************BINARY-SEARCH ENDS*********************************************** // *********************************GRAPHS-STARTS**************************************************** // *******----SEGMENT TREE IMPLEMENT---***** // -------------START--------------- void buildTree (int[] arr,int[] tree,int start,int end,int treeNode){ if(start==end){ tree[treeNode]=arr[start]; return; } buildTree(arr,tree,start,end,2*treeNode); buildTree(arr,tree,start,end,2*treeNode+1); tree[treeNode]=tree[treeNode*2]+tree[2*treeNode+1]; } void updateTree(int[] arr,int[] tree,int start,int end,int treeNode,int idx,int value){ if(start==end){ arr[idx]=value; tree[treeNode]=value; return; } int mid=(start+end)/2; if(idx>mid)updateTree(arr,tree,mid+1,end,2*treeNode+1,idx,value); else updateTree(arr,tree,start,mid,2*treeNode,idx,value); tree[treeNode]=tree[2*treeNode]+tree[2*treeNode+1]; } long query(int[]arr,int[]tree,int start,int end,int treeNode,int qleft,int qright) { if(start>=qleft&&end<=qright)return tree[treeNode]; if(start>qright||end<qleft)return 0; int mid=(start+end)/2; long valLeft=query(arr,tree,start,mid-1,treeNode*2,qleft,qright); long valRight=query(arr,tree,mid+1,end,treeNode*2+1,qleft,qright); return valLeft+valRight; } // -------------ENDS--------------- //***********************DSU IMPLEMENT START************************* static int parent[]; static int rank[]; static int[]Size; static void makeSet(int n){ parent=new int[n]; rank=new int[n]; Size=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; rank[i]=0; Size[i]=1; } } static void union(int u,int v){ u=findpar(u); v=findpar(v); if(u==v)return; if(rank[u]<rank[v]) { parent[u]=v; Size[v]+=Size[u]; } else if(rank[v]<rank[u]) { parent[v]=u; Size[u]+=Size[v]; } else{ parent[v]=u; rank[u]++; Size[u]+=Size[v]; } } private static int findpar(int node){ if(node==parent[node])return node; return parent[node]=findpar(parent[node]); } // *********************DSU IMPLEMENT ENDS************************* // ****__________PRIMS ALGO______________________**** private static int prim(ArrayList<node>[] adj,int N,int node) { int key[] = new int[N+1]; int parent[] = new int[N+1]; boolean mstSet[] = new boolean[N+1]; for(int i = 0;i<N;i++) { key[i] = 100000000; mstSet[i] = false; } PriorityQueue<node> pq = new PriorityQueue<node>(N, new node()); key[node] = 0; parent[node] = -1; pq.add(new node( node,key[node])); for(int i = 0;i<N-1;i++) { int u = pq.poll().getV(); mstSet[u] = true; for(node it: adj[u]) { if(mstSet[it.getV()] == false && it.getW() < key[it.getV()]) { parent[it.getV()] = u; key[it.getV()] = (int) it.getW(); pq.add(new node(it.getV(), key[it.getV()])); } } } int sum=0; for(int i=1;i<N;i++) { System.out.println(key[i]); sum+=key[i]; } System.out.println(sum); return sum; } // ****____________DIJKSTRAS ALGO___________**** static int[]dist; static int dijkstra(int u,int n,ArrayList<node>adj[]) { long[]path=new long[n]; dist=new int[n]; Arrays.fill(dist,Integer.MAX_VALUE); dist[u]=0; path[0]=1; PriorityQueue<node>pq=new PriorityQueue<node>(new node()); pq.add(new node(u,0)); while(!pq.isEmpty()) { node v=pq.poll(); if(dist[v.getV()]<v.getW())continue; for(node it:adj[v.getV()]) { if(dist[it.getV()]>it.getW()+dist[v.getV()]) { dist[it.getV()]=(int) (it.getW()+dist[v.getV()]); pq.add(new node(it.getV(),dist[it.getV()])); path[it.getV()]=path[v.getV()]; } else if(dist[it.getV()]==it.getW()+dist[v.getV()]) { path[it.getV()]+=path[v.getV()]; } } } int sum=0; for(int i=1;i<n;i++){ System.out.println(dist[i]); sum+=dist[i]; } return sum; } private static void setGraph(int n,int m){ vis=new boolean[n+1]; indeg=new int[n+1]; // adj=new ArrayList<ArrayList<Integer>>(); // for(int i=0;i<=n;i++)adj.add(new ArrayList<>()); // for(int i=0;i<m;i++){ // int u=s.nextInt(),v=s.nextInt(); // adj.get(u).add(v); // adj.get(v).add(u); // } adj=new ArrayList[n+1]; // backadj=new ArrayList[n+1]; for(int i=0;i<=n;i++){ adj[i]=new ArrayList<Integer>(); // backadj[i]=new ArrayList<Integer>(); } for(int i=0;i<m;i++){ int u=s.nextInt(),v=s.nextInt(); adj[u].add(v); adj[v].add(u); // backadj[v].add(u); indeg[v]++; indeg[u]++; } // weighted adj // adj=new ArrayList[n+1]; // for(int i=0;i<=n;i++){ // adj[i]=new ArrayList<node>(); // } // for(int i=0;i<m;i++){ // int u=s.nextInt(),v=s.nextInt(); // long w=s.nextInt(); // adj[u].add(new node(v,w)); //// adj[v].add(new node(u,w)); // } } // *********************************GRAPHS-ENDS**************************************************** static int[][] dirs8 = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}}; static int[][] dirs4 = {{1,0},{-1,0},{0,1},{0,-1}}; //d-u-r-l static long MOD=(long) (1e9+7); static int prebitsum[][]; static boolean[] vis; static int[]indeg; // static ArrayList<ArrayList<Integer>>adj; static ArrayList<Integer> adj[]; static ArrayList<Integer> backadj[]; static FastReader s = new FastReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { // sieve(); // computeFact((int)1e7+1,MOD); // prebitsum=new int[2147483648][31]; // presumbit(prebitsum); // powof2S(); // // try { int tt = s.nextInt(); // int tt=1; for(int i=1;i<=tt;i++) { solver(); } out.close(); // catch(Exception e) {return;} } private static void solver() { n=s.nextInt(); int k=s.nextInt(); int[]a=s.rdia(n-1); adj=new ArrayList[n+1]; for(int i=0;i<=n;i++){ adj[i]=new ArrayList<Integer>(); } for(int i=0;i<n-1;i++) { adj[i+2].add(a[i]); adj[a[i]].add(i+2); } // for(ArrayList<Integer> it:adj) { // out.println(it); // } int ans=n; int lo=1,hi=n; while(lo<=hi) { int mid=(lo+hi)/2; if(isvalid(mid,k)) { ans=mid; hi=mid-1; } else lo=mid+1; } out.println(ans); } static int moves,n; private static boolean isvalid(int mid, int k) { moves=0; if(mid>1)dfs(mid,1,0); else moves=n-1-adj[1].size(); return moves<=k; } private static int dfs(int mid, int i, int j) { int height=1; for(int it:adj[i]) { if(it==j)continue; height=max(height,1+dfs(mid,it,i)); } if(height==mid&&j!=1&&i!=1){ moves++; return 0; } return height; } /* *********************BITS && TOOLS &&DEBUG STARTS***********************************************/ static boolean issafe(int i, int j, int r,int c,boolean[][]vis){ if (i < 0 || j < 0 || i >= r || j >= c||vis[i][j]==true)return false; else return true; } static void presumbit(int[][]prebitsum) { for(int i=1;i<=200000;i++) { int z=i; int j=0; while(z>0) { if((z&1)==1) { prebitsum[i][j]+=(prebitsum[i-1][j]+1); }else { prebitsum[i][j]=prebitsum[i-1][j]; } z=z>>1; j++; } } } static void countOfSetBit(long[]a) { for(int j=30;j>=0;j--) { int cnt=0; for(long i:a) { if((i&1<<j)==1)cnt++; } // printing the current no set bit in all array element System.out.println(cnt); } } public static String revStr(String str){String input = str;StringBuilder input1 = new StringBuilder();input1.append(input);input1.reverse();return input1.toString();} static void printA(long[] x) {for(int i=0;i<x.length;i++)System.out.print(x[i]+" ");System.out.println();} static void printA(int[] x) {for(int i=0;i<x.length;i++)System.out.print(x[i]+" ");System.out.println();} private static void printA(char[] x) {for(int i=0;i<x.length;i++)System.out.print(x[i]+" ");System.out.println();} static void pc2d(boolean[][] vis) { int n=vis.length; int m=vis[0].length; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print(vis[i][j]+" "); } System.out.println(); } } static void pi2d(char[][] a) { int n=a.length; int m=a[0].length; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } static void p1d(int[]a) { for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } // *****************BITS && TOOLS &&DEBUG ENDS*********************************************** } // **************************I/O************************* class FastReader { public BufferedReader reader; public StringTokenizer tokenizer; public FastReader(InputStream stream) {reader = new BufferedReader(new InputStreamReader(stream), 32768);tokenizer = null;} public String next() {while (tokenizer == null || !tokenizer.hasMoreTokens()) {try {tokenizer = new StringTokenizer(reader.readLine());} catch (IOException e) {throw new RuntimeException(e);}}return tokenizer.nextToken();} public int nextInt(){ return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() {String str = "";try {str = reader.readLine();}catch (IOException e) {e.printStackTrace();}return str;} public int[] rdia(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = nextInt();return a;} public long[] rdla(int n) {long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nextLong();return a;} public Integer[] rdIa(int n) {Integer[] a = new Integer[n];for (int i = 0; i < n; i++) a[i] =nextInt();return a;} public Long[] rdLa(int n) {Long[] a = new Long[n];for (int i = 0; i < n; i++) a[i] = nextLong();return a;} } class dsu{ int n; static int parent[]; static int rank[]; static int[]Size; public dsu(int n) {this.n=n;this.parent=new int[n];this.rank=new int[n];this.Size=new int[n]; for(int i=0;i<n;i++){parent[i]=i;rank[i]=0;Size[i]=1;} } static int findpar(int node) {if(node==parent[node])return node;return parent[node]=findpar(parent[node]);} static void union(int u,int v){ u=findpar(u);v=findpar(v); if(u!=v) { if(rank[u]<rank[v]) {parent[u]=v;Size[v]+=Size[u];} else if(rank[v]<rank[u]) {parent[v]=u;Size[u]+=Size[v];} else{parent[v]=u;rank[u]++;Size[u]+=Size[v];} } } } class pair{ int x;int y; long u,v; public pair(int x,int y){this.x=x;this.y=y;} public pair(long u,long v) {this.u=u;this.v=v;} } class Tuple{ String str;int x;int y; public Tuple(String str,int x,int y) { this.str=str; this.x=x; this.y=y; } } class node implements Comparator<node>{ private int v; private long w; node(int _v, long _w) { v = _v; w = _w; } node() {} int getV() { return v; } long getW() { return w; } @Override public int compare(node node1, node node2) { if (node1.w < node2.w) return -1; if (node1.w > node2.w) return 1; return 0; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
2b611652c0d7ff692542dec02fe68c6b
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.StringTokenizer; public class D { static final long mod = (long) 1e9 + 7l; private static void solve(int tt){ int n = fs.nextInt(); int k= fs.nextInt(); int arr[] = new int[n]; for (int i = 1; i < n; i++) { arr[i]=fs.nextInt()-1; } int lo = 0, hi = n - 1; while (hi - lo > 1) { int x = (lo + hi) / 2; int steps = 0; int[] h =new int[n]; for (int i = n - 1; i > 0; i--) { if (h[i] == x - 1 && arr[i] != 0) { steps++; } else { h[arr[i]] = Math.max(h[arr[i]], h[i] + 1); } } if (steps <= k) { hi = x; } else { lo = x; } } out.println(hi); } private static void solve2(int tt){ int n = fs.nextInt(); int k= fs.nextInt(); int chs[] = new int[n]; int h[] = new int[n]; int[] par = new int[n]; for (int i = 0; i < n - 1; i++) { int p = fs.nextInt()-1; par[i+1]= p; chs[p]++; h[i+1]= 1+h[p]; } // out.println(Arrays.toString(chs)); // out.println(Arrays.toString(h)); // out.println(Arrays.toString(par)); PriorityQueue<int[]> pq = new PriorityQueue<>((int[] a, int[] b) -> b[1]-a[1]); for (int i = 1; i < n; i++) { if(h[i]>1 && chs[i]==0)pq.offer(new int[] {i,h[i]} ); //leaf node with h>1 } while (!pq.isEmpty() && k>0){ k--; int []curr = pq.poll(); int node = curr[0]; int mh = curr[1]; int newHeight = (mh+1)/2; //handle even odd heights if(newHeight>1){ // already leaf and if h >1 pq.offer(new int[]{node, newHeight}); } while(newHeight>1){ //detach h[node]= newHeight; node = par[node]; newHeight--; } int parent = par[node]; chs[parent]--; par[node] = 0; // attach to root h[node]=1; // par is root if(chs[parent]==0 && h[parent]>1){ // became leaf and h >1 pq.offer(new int[]{parent, h[parent]}); } } int max = 0; for (int i = 0; i < n; i++) { max = Math.max(h[i], max); } out.println(max); } private static int[] sortByCollections(int[] arr) { ArrayList<Integer> ls = new ArrayList<>(arr.length); for (int i = 0; i < arr.length; i++) { ls.add(arr[i]); } Collections.sort(ls); for (int i = 0; i < arr.length; i++) { arr[i] = ls.get(i); } return arr; } public static void main(String[] args) { fs = new FastScanner(); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); int t = fs.nextInt(); for (int i = 1; i <= t; i++) solve(t); out.close(); // System.err.println( System.currentTimeMillis() - s + "ms" ); } static boolean DEBUG = true; static PrintWriter out; static FastScanner fs; static void trace(Object... o) { if (!DEBUG) return; System.err.println(Arrays.deepToString(o)); } static void pl(Object o) { out.println(o); } static void p(Object o) { out.print(o); } static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } static void sieveOfEratosthenes(int n, int factors[]) { factors[1] = 1; for (int p = 2; p * p <= n; p++) { if (factors[p] == 0) { factors[p] = p; for (int i = p * p; i <= n; i += p) factors[i] = p; } } } static long mul(long a, long b) { return a * b % mod; } static long fact(int x) { long ans = 1; for (int i = 2; i <= x; i++) ans = mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp == 0) return 1; long half = fastPow(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static long modInv(long x) { return fastPow(x, mod - 2); } static long nCk(int n, int k) { return mul(fact(n), mul(modInv(fact(k)), modInv(fact(n - k)))); } 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(); } 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()); } } static class _Scanner { InputStream is; _Scanner(InputStream is) { this.is = is; } byte[] bb = new byte[1 << 15]; int k, l; byte getc() throws IOException { if (k >= l) { k = 0; l = is.read(bb); if (l < 0) return -1; } return bb[k++]; } byte skip() throws IOException { byte b; while ((b = getc()) <= 32) ; return b; } int nextInt() throws IOException { int n = 0; for (byte b = skip(); b > 32; b = getc()) n = n * 10 + b - '0'; return n; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
3ba1b53d58d8a4e42aa2def6a3cddbcc
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; // res.append("Case #"+(p+1)+": "+hh+" \n"); ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class D_Reset_K_Edges{ 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(); int k=s.nextInt(); ArrayList<ArrayList<Integer>> list = new ArrayList<>(n+3); for(int i=0;i<=n;i++){ ArrayList<Integer> obj = new ArrayList<>(); list.add(obj); } for(int i=2;i<=n;i++){ int hh=s.nextInt(); list.get(i).add(hh); list.get(hh).add(i); } int start=0; int end=n; int mid=0; while(start<end){ mid=(start+end)/2; if(start+1==end){ break; } int yoyo=0; int nice[]= new int[n+1]; int dp[]= new int[n+1]; dfs(list,nice,dp,1,0,mid-1); yoyo=dp[1]; if(yoyo<=k){ end=mid; } else{ start=mid; } } res.append(end+"\n"); p++;} out.println(res); out.close(); } private static void dfs(ArrayList<ArrayList<Integer>> list, int[] nice, int[] dp, int i, int par,int lev) { if(list.get(i).size()==1 && list.get(i).get(0)==par){ //leaf dp[i]=0; nice[i]=0; return; } int alpha=0; int beta=-1; for(int j=0;j<list.get(i).size();j++){ int num=list.get(i).get(j); if(num!=par){ dfs(list,nice,dp,num,i,lev); alpha+=dp[num]; int yoyo=nice[num]; if(yoyo==lev && i!=1){ alpha++; } else{ beta=Math.max(beta,yoyo); } } } dp[i]=alpha; nice[i]=beta+1; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
cd977778b77572bbd30b1560c20fdfb4
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.lang.*; import java.math.BigInteger; import java.util.*; public class Solution { public static void main(String[] args) throws Exception { FastScanner fs = new FastScanner(); int t = fs.nextInt(); while (t-- != 0) { int n = fs.nextInt(), k = fs.nextInt(); List<Integer>[] g = new List[n + 1]; for (int i = 1; i <= n; ++i) { g[i] = new ArrayList<>(); } for (int i = 2; i <= n; ++i) { int tmp = fs.nextInt(); g[tmp].add(i); } int lo = 1, hi = n - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (check(g, mid, k)) { hi = mid - 1; } else { lo = mid + 1; } } out.println(lo); } out.flush(); out.close(); } public static boolean check(List<Integer>[] g, int dep, int cnt) { /* Deque<int[]> dq = new ArrayDeque<>(); for (int i = 2; i <= n; ++i) { if (g[i].size() == 0) dq.offer(new int[] {i, 1}); } boolean[] visited = new boolean[n + 1]; visited[1] = true; int cur = 0; while (!dq.isEmpty()) { int[] v = dq.pollFirst(); if (visited[v[0]]) continue; visited[v[0]] = true; if (v[1] == dep) { if (p[v[0]] == 1) continue; cur++; dq.offerLast(new int[] {p[v[0]], 1}); } else { dq.offer(new int[] {p[v[0]], v[1] + 1}); } } */ return dfs(g, dep, 1)[1] <= cnt; } public static int[] dfs(List<Integer>[] g, int dep, int ptr) { int[] ans = new int[2]; ans[0] = -1; for (int child : g[ptr]) { int[] v = dfs(g, dep, child); ans[0] = Math.max(ans[0], v[0] % dep); ans[1] += v[1]; if (v[0] == dep && ptr != 1) ans[1]++; } if (ans[0] == -1) ans[0] = 1; else ans[0]++; return ans; } static final Random random = new Random(); static void ruffleSort(long arr[]) { int n = arr.length; for(int i = 0; i < n; i++) { int j = random.nextInt(n); long temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static PrintWriter out = new PrintWriter(System.out); static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
5d647a7f757c4ec727a78c4880acc8b2
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class ResetKEdges_1739D { static List<Integer>[] children; static int[] parent; static int count; @SuppressWarnings("unchecked") public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t -- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); children = new List[n + 1]; parent = new int[n + 1]; for(int i = 1; i <= n; i ++) children[i] = new ArrayList<>(); st = new StringTokenizer(br.readLine()); for(int i = 2; i <= n; i ++) { parent[i] = Integer.parseInt(st.nextToken()); children[parent[i]].add(i); } int l = 1, r = n - 1; while(l <= r) { int m = (l + r) / 2; count = 0; dfs(1, m); if(count > k) { l = m + 1; } else { r = m - 1; } } System.out.println(l); } } private static int dfs(int u, int limit) { int maxLen = 0; for(int v : children[u]) { int currLen = dfs(v, limit); if(currLen == limit && u != 1) { count ++; } else { maxLen = Math.max(maxLen, currLen); } } return maxLen + 1; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
22f12f2cf8e44ab184b8056d234ef91b
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; public class assignment { static int cuts = 0; private static int dfs(ArrayList<ArrayList<Integer>> graph, int root, int heightReq, int parent){ int height = 0; for(int i:graph.get(root)){ height=Math.max(height, dfs(graph,i, heightReq, root)); } if(height+1==heightReq && parent!=0 && root!=0){ cuts++; return 0; } return height+1; } private static boolean isValid(int height, int k, ArrayList<ArrayList<Integer>> graph){ cuts = 0; if(height>1){ dfs(graph, 0, height,-1); }else{ cuts = graph.size()-1-graph.get(0).size(); } return cuts<=k; } public static void main(String args[]) { Scanner s=new Scanner(System.in); int t = s.nextInt(); while(t-->0){ int n = s.nextInt(), k = s.nextInt(); ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); for(int i=0;i<n;i++){ graph.add(new ArrayList<>()); } for(int i=1;i<n;i++){ int parent=s.nextInt(); graph.get(parent-1).add(i); } int low = 1, high = n; while(low<=high){ int mid = (low+high)/2; boolean flag = isValid(mid,k,graph); if(flag) { high=mid-1; } else low=mid+1; } System.out.println(low); } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
a9523efd8fed7cfee78a5fcc26ed23aa
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.time.Clock; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.function.Supplier; public class Solution { private void solve() throws IOException { int n = nextInt(); int k = nextInt(); Graph g = new Graph(n); for (int i = 1; i < n; i++) { g.addDirect(nextInt() - 1, i); } int left = 1; int right = n; while (left < right) { int m = (left + right) / 2; if (m > 1 && f(0, -1, m, g).x <= k) { right = m; } else { left = m + 1; } } out.println(right - 1); } private Pii f(int v, int pv, int maxDepth, Graph g) { int res = 0; int depth = 1; for (int nv : g.neighbors(v)) { Pii t = f(nv, v, maxDepth, g); res += t.x; depth = Math.max(depth, t.y + 1); } if (depth == maxDepth - 1 && pv > 0) { res++; depth = -1; } return new Pii(res, depth); } private static class Pii implements Comparable<Pii> { // not today, evil hacker private static final int hashMultiplier = BigInteger.valueOf(new Random().nextInt(100000) + 100).nextProbablePrime().intValue(); private int x; private int y; public Pii(int x, int y) { this.x = x; this.y = y; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pii pii = (Pii) o; if (x != pii.x) return false; return y == pii.y; } public int hashCode() { return hashMultiplier * x + y; } public String toString() { return "(" + x + ", " + y + ")"; } public int compareTo(Pii o) { int c = Integer.compare(x, o.x); return c != 0 ? c : Integer.compare(y, o.y); } } private static class Graph { private ArrayList<Integer>[] g; public Graph(int n) { g = new ArrayList[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } } public void addDirect(int u, int v) { g[u].add(v); } public ArrayList<Integer> neighbors(int v) { return g[v]; } } private static final boolean runNTestsInProd = true; private static final boolean printCaseNumber = false; private static final boolean assertInProd = false; private static final boolean logToFile = false; private static final boolean readFromConsoleInDebug = false; private static final boolean writeToConsoleInDebug = true; private static final boolean testTimer = false; private static Boolean isDebug = null; private BufferedReader in; private StringTokenizer line; private PrintWriter out; public static void main(String[] args) throws Exception { isDebug = Arrays.asList(args).contains("DEBUG_MODE"); if (isDebug) { log = logToFile ? new PrintWriter("logs/j_solution_" + System.currentTimeMillis() + ".log") : new PrintWriter(System.out); clock = Clock.systemDefaultZone(); } new Solution().run(); } private void run() throws Exception { in = new BufferedReader(new InputStreamReader(!isDebug || readFromConsoleInDebug ? System.in : new FileInputStream("input.txt"))); out = !isDebug || writeToConsoleInDebug ? new PrintWriter(System.out) : new PrintWriter("output.txt"); try (Timer totalTimer = new Timer("total")) { int t = runNTestsInProd || isDebug ? nextInt() : 1; for (int i = 0; i < t; i++) { if (printCaseNumber) { out.print("Case #" + (i + 1) + ": "); } if (testTimer) { try (Timer testTimer = new Timer("test #" + (i + 1))) { solve(); } } else { solve(); } if (isDebug) { out.flush(); } } } in.close(); out.flush(); out.close(); } private void println(Object... objects) { boolean isFirst = true; for (Object o : objects) { if (!isFirst) { out.print(" "); } else { isFirst = false; } out.print(o.toString()); } out.println(); } private int[] nextIntArray(int n) throws IOException { return nextIntArray(n, 0); } private int[] nextIntArray(int n, int delta) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt() + delta; } return res; } private long[] nextLongArray(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private char[] nextTokenChars() throws IOException { return nextToken().toCharArray(); } private String nextToken() throws IOException { while (line == null || !line.hasMoreTokens()) { line = new StringTokenizer(in.readLine()); } return line.nextToken(); } private static void assertPredicate(boolean p) { if ((isDebug || assertInProd) && !p) { throw new RuntimeException(); } } private static void assertPredicate(boolean p, String message) { if ((isDebug || assertInProd) && !p) { throw new RuntimeException(message); } } private static <T> void assertNotEqual(T unexpected, T actual) { if ((isDebug || assertInProd) && Objects.equals(actual, unexpected)) { throw new RuntimeException("assertNotEqual: " + unexpected + " == " + actual); } } private static <T> void assertEqual(T expected, T actual) { if ((isDebug || assertInProd) && !Objects.equals(actual, expected)) { throw new RuntimeException("assertEqual: " + expected + " != " + actual); } } private static PrintWriter log = null; private static Clock clock = null; private static void log(Object... objects) { log(true, objects); } private static void logNoDelimiter(Object... objects) { log(false, objects); } private static void log(boolean printDelimiter, Object[] objects) { if (isDebug) { StringBuilder sb = new StringBuilder(); sb.append(LocalDateTime.now(clock)).append(" - "); boolean isFirst = true; for (Object o : objects) { if (!isFirst && printDelimiter) { sb.append(" "); } else { isFirst = false; } sb.append(o.toString()); } log.println(sb); log.flush(); } } private static class Timer implements Closeable { private final String label; private final long startTime = isDebug ? System.nanoTime() : 0; public Timer(String label) { this.label = label; } @Override public void close() throws IOException { if (isDebug) { long executionTime = System.nanoTime() - startTime; String fraction = Long.toString(executionTime / 1000 % 1_000_000); logNoDelimiter("Timer[", label, "]: ", executionTime / 1_000_000_000, '.', "00000".substring(0, 6 - fraction.length()), fraction, 's'); } } } private static <T> T timer(String label, Supplier<T> f) throws Exception { if (isDebug) { try (Timer timer = new Timer(label)) { return f.get(); } } else { return f.get(); } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
cd4852643f76c64e96a716bd60bca6c9
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class Solution { private static boolean useInFile = false; private static boolean useOutFile = false; public static void main(String args[]) throws IOException { InOut inout = new InOut(); Resolver resolver = new Resolver(inout); resolver.solve(); inout.flush(); } private static class Resolver { final long LONG_INF = (long) 1e18; final int INF = (int) (1e9 + 7); final int MOD = 998244353; long f[], inv[]; InOut inout; Resolver(InOut inout) { this.inout = inout; } void initF(int n, int mod) { f = new long[n + 1]; f[1] = 1; for (int i = 2; i <= n; i++) { f[i] = (f[i - 1] * i) % mod; } } void initInv(int n, int mod) { inv = new long[n + 1]; inv[n] = pow(f[n], mod - 2, mod); for (int i = inv.length - 2; i >= 0; i--) { inv[i] = inv[i + 1] * (i + 1) % mod; } } long cmn(int n, int m, int mod) { return f[n] * inv[m] % mod * inv[n - m] % mod; } int d[] = {0, -1, 0, 1, 0}; boolean legal(int r, int c, int n, int m) { return r >= 0 && r < n && c >= 0 && c < m; } int ans = 0; int dfs(int f, int dep) { List<Integer> es = adj[f]; int rs = 0; for (int i = 0; i < es.size(); i++) { int t = es.get(i); int val = dfs(t, dep) + 1; if (f != 1 && val == dep) { ans++; } else { rs = Math.max(rs, val); } } return rs; } void solve() throws IOException { int tt = 1; boolean hvt = true; if (hvt) { tt = nextInt(); // tt = Integer.parseInt(nextLine()); } // initF(200001, MOD); // initInv(200001, MOD); for (int cs = 1; cs <= tt; cs++) { long rs = 0; boolean ok = true; int n = nextInt(); int k = nextInt(); int p[] = anInt(2, n); adj = new List[n + 1]; for (int i = 1; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 2; i <= n; i++) { adj[p[i]].add(i); } int l = 1, r = n; while (l < r) { int m = (l + r) / 2; ans = 0; dfs(1, m); if (ans > k) { l = m + 1; } else { r = m; } } rs = l; // format("%s", ok ? "YES" : "NO"); // format("%f", ans); format("%d", rs); // format("Case #%d: %d", cs, rs); if (cs < tt) { format("\n"); } // flush(); } } private void updateSegTree(int n, long l, SegmentTree lft) { long lazy; lazy = 1; for (int j = 1; j <= l; j++) { lazy = (lazy + cmn((int) l, j, INF)) % INF; lft.modify(1, j, j, lazy); } lft.modify(1, (int) (l + 1), n, lazy); } String next() throws IOException { return inout.next(); } String next(int n) throws IOException { return inout.next(n); } String nextLine() throws IOException { return inout.nextLine(); } int nextInt() throws IOException { return inout.nextInt(); } long nextLong(int n) throws IOException { return inout.nextLong(n); } int[] anInt(int i, int j) throws IOException { int a[] = new int[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextInt(); } return a; } long[] anLong(int i, int j, int len) throws IOException { long a[] = new long[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextLong(len); } return a; } void print(String s, boolean nextLine) { inout.print(s, nextLine); } void format(String format, Object... obj) { inout.format(format, obj); } void flush() { inout.flush(); } void swap(long a[], int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } int getP(int x, int p[]) { if (p[x] == 0 || p[x] == x) { return x; } return p[x] = getP(p[x], p); } void union(int x, int y, int p[]) { if (x < y) { p[y] = x; } else { p[x] = y; } } boolean topSort() { int n = adj2.length - 1; int d[] = new int[n + 1]; for (int i = 1; i <= n; i++) { for (int j = 0; j < adj2[i].size(); j++) { d[adj2[i].get(j)[0]]++; } } List<Integer> list = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (d[i] == 0) { list.add(i); } } for (int i = 0; i < list.size(); i++) { for (int j = 0; j < adj2[list.get(i)].size(); j++) { int t = adj2[list.get(i)].get(j)[0]; d[t]--; if (d[t] == 0) { list.add(t); } } } return list.size() == n; } class SegmentTreeNode { long defaultVal = 0; int l, r; long val = defaultVal, lazy = defaultVal; SegmentTreeNode(int l, int r) { this.l = l; this.r = r; } } class SegmentTree { SegmentTreeNode tree[]; long defaultVal = 0; long inf = Long.MIN_VALUE; long mod = INF; int type = 0; int MODIFY_VAL = 1; int MODIFY_LAZY = 2; int MODIFY_ALL = 3; SegmentTree(int n) { this(n, 0); } SegmentTree(int n, int type) { this.type = type; assert n > 0; tree = new SegmentTreeNode[n << 2]; } SegmentTree build(int k, int l, int r) { if (l > r) { return this; } if (null == tree[k]) { tree[k] = new SegmentTreeNode(l, r); } if (l == r) { return this; } int mid = (l + r) >> 1; build(k << 1, l, mid); build(k << 1 | 1, mid + 1, r); return this; } void pushDown(int k) { if (tree[k].l == tree[k].r) { return; } long lazy = tree[k].lazy; modify(tree[k << 1], MODIFY_ALL, lazy); modify(tree[k << 1 | 1], MODIFY_ALL, lazy); tree[k].lazy = defaultVal; } void modify(int k, int l, int r, long val) { if (l > r) { return; } if (tree[k].l >= l && tree[k].r <= r) { modify(tree[k], MODIFY_ALL, val); return; } int mid = (tree[k].l + tree[k].r) >> 1; if (mid >= l) { modify(k << 1, l, r, val); } if (mid + 1 <= r) { modify(k << 1 | 1, l, r, val); } tree[k].val = Math.max(tree[k << 1].val, tree[k << 1 | 1].val); } long query(int k, int l, int r) { if (tree[k].l > r || tree[k].r < l) { return inf; } if (tree[k].lazy != defaultVal) { pushDown(k); } if (tree[k].l >= l && tree[k].r <= r) { return tree[k].val; } long ans = Math.max(query(k << 1, l, r), query(k << 1 | 1, l, r)); if (tree[k].l < tree[k].r) { tree[k].val = Math.max(tree[k << 1].val, tree[k << 1 | 1].val); } return ans; } private void modify(SegmentTreeNode node, int x, long val) { switch (type) { case 0: if (x == MODIFY_VAL) { node.val += val; } else if (x == MODIFY_LAZY) { node.lazy += val; } else { node.val += val; node.lazy += val; } break; case 1: if (x == MODIFY_VAL) { node.val = node.val * val % mod; } else if (x == MODIFY_LAZY) { node.lazy = node.lazy * val % mod; } else { node.val = node.val * val % mod; node.lazy = node.lazy * val % mod; } break; } } } class BinaryIndexedTree { int n = 1; long C[]; BinaryIndexedTree(int sz) { while (n <= sz) { n <<= 1; } C = new long[n]; } int lowbit(int x) { return x & -x; } void add(int x, long val) { while (x < n) { C[x] += val; x += lowbit(x); } } long getSum(int x) { long res = 0; while (x > 0) { res += C[x]; x -= lowbit(x); } return res; } int binSearch(long sum) { if (sum == 0) { return 0; } int n = C.length; int mx = 1; while (mx < n) { mx <<= 1; } int res = 0; for (int i = mx / 2; i >= 1; i >>= 1) { if (C[res + i] < sum) { sum -= C[res + i]; res += i; } } return res + 1; } } int mnS; int mxS; Map<Integer, TrieNode> SS = new HashMap<>(); class TrieNode { int cnt = 0; boolean isMin = false; boolean isMax = false; int mnIdx = 26; int mxIdx = -1; TrieNode next[]; TrieNode() { next = new TrieNode[26]; } private void insert(TrieNode trie, char ch[], int i, int j) { while (i < ch.length) { int idx = ch[i] - 'a'; if (null == trie.next[idx]) { trie.next[idx] = new TrieNode(); } trie.cnt++; int lastMnIdx = trie.mnIdx; int lastMxIdx = trie.mxIdx; trie.mnIdx = Math.min(trie.mnIdx, idx); trie.mxIdx = Math.max(trie.mxIdx, idx); if (trie.isMin && lastMnIdx != trie.mnIdx) { if (lastMnIdx != 26) { notMin(trie.next[lastMnIdx]); } trie.next[trie.mnIdx].isMin = true; } if (trie.isMax && lastMxIdx != trie.mxIdx) { if (lastMxIdx >= 0) { notMax(trie.next[lastMxIdx]); } trie.next[trie.mxIdx].isMax = true; } trie = trie.next[idx]; i++; } SS.put(j + 1, trie); if (trie.cnt == 0) { if (trie.isMin) { mnS = j + 1; } if (trie.isMax) { mxS = j + 1; } } } private void notMin(TrieNode trie) { while (null != trie) { trie.isMin = false; int val = trie.mnIdx; if (val >= 26 || val < 0 || null == trie.next[val]) { break; } trie = trie.next[val]; } } private void notMax(TrieNode trie) { while (null != trie) { trie.isMax = false; int val = trie.mxIdx; if (val >= 26 || val < 0 || null == trie.next[val]) { break; } trie = trie.next[val]; } } } //Binary tree class TreeNode { int val; int tier = -1; TreeNode parent; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } //binary tree dfs void tierTree(TreeNode root) { if (null == root) { return; } if (null != root.parent) { root.tier = root.parent.tier + 1; } else { root.tier = 0; } tierTree(root.left); tierTree(root.right); } //LCA start TreeNode[][] lca; TreeNode[] tree; void lcaDfsTree(TreeNode root) { if (null == root) { return; } tree[root.val] = root; TreeNode nxt = root.parent; int idx = 0; while (null != nxt) { lca[root.val][idx] = nxt; nxt = lca[nxt.val][idx]; idx++; } lcaDfsTree(root.left); lcaDfsTree(root.right); } TreeNode lcaTree(TreeNode root, int n, TreeNode x, TreeNode y) throws IOException { if (null == root) { return null; } if (-1 == root.tier) { tree = new TreeNode[n + 1]; tierTree(root); } if (null == lca) { lca = new TreeNode[n + 1][31]; lcaDfsTree(root); } int z = Math.abs(x.tier - y.tier); int xx = x.tier > y.tier ? x.val : y.val; while (z > 0) { final int zz = z; int l = (int) BinSearch.bs(0, 31 , k -> zz < (1 << k)); xx = lca[xx][l].val; z -= 1 << l; } int yy = y.val; if (x.tier <= y.tier) { yy = x.val; } while (xx != yy) { final int xxx = xx; final int yyy = yy; int l = (int) BinSearch.bs(0, 31 , k -> (1 << k) <= tree[xxx].tier && lca[xxx][(int) k] != lca[yyy][(int) k]); xx = lca[xx][l].val; yy = lca[yy][l].val; } return tree[xx]; } //LCA end //graph List<Integer> adj[]; List<int[]> adj2[]; void initGraph(int n, int m, boolean hasW, boolean directed, int type) throws IOException { if (type == 1) { adj = new List[n + 1]; } else { adj2 = new List[n + 1]; } for (int i = 1; i <= n; i++) { if (type == 1) { adj[i] = new ArrayList<>(); } else { adj2[i] = new ArrayList<>(); } } for (int i = 0; i < m; i++) { int f = nextInt(); int t = nextInt(); if (type == 1) { adj[f].add(t); if (!directed) { adj[t].add(f); } } else { int w = hasW ? nextInt() : 0; adj2[f].add(new int[]{t, w}); if (!directed) { adj2[t].add(new int[]{f, w}); } } } } void getDiv(Map<Integer, Integer> map, int n) { int sqrt = (int) Math.sqrt(n); for (int i = 2; i <= sqrt; i++) { int cnt = 0; while (n % i == 0) { cnt++; n /= i; } if (cnt > 0) { map.put(i, cnt); } } if (n > 1) { map.put(n, 1); } } boolean[] generatePrime(int n) { boolean p[] = new boolean[n + 1]; p[2] = true; for (int i = 3; i <= n; i += 2) { p[i] = true; } for (int i = 3; i <= Math.sqrt(n); i += 2) { if (!p[i]) { continue; } for (int j = i * i; j <= n; j += i << 1) { p[j] = false; } } return p; } boolean isPrime(long n) { //determines if n is a prime number int p[] = {2, 3, 5, 233, 331}; int pn = p.length; long s = 0, t = n - 1;//n - 1 = 2^s * t while ((t & 1) == 0) { t >>= 1; ++s; } for (int i = 0; i < pn; ++i) { if (n == p[i]) { return true; } long pt = pow(p[i], t, n); for (int j = 0; j < s; ++j) { long cur = llMod(pt, pt, n); if (cur == 1 && pt != 1 && pt != n - 1) { return false; } pt = cur; } if (pt != 1) { return false; } } return true; } long llMod(long a, long b, long mod) { return (a * b - (long) ((double) a / mod * b + 0.5) * mod + mod) % mod; // long r = 0; // a %= mod; // b %= mod; // while (b > 0) { // if ((b & 1) == 1) { // r = (r + a) % mod; // } // b >>= 1; // a = (a << 1) % mod; // } // return r; } long pow(long a, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans = ans * a; } a = a * a; n >>= 1; } return ans; } long pow(long a, long n, long mod) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans = llMod(ans, a, mod); } a = llMod(a, a, mod); n >>= 1; } return ans; } private long[][] initC(int n) { long c[][] = new long[n][n]; for (int i = 0; i < n; i++) { c[i][0] = 1; } for (int i = 1; i < n; i++) { for (int j = 1; j <= i; j++) { c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; } } return c; } /** * ps: n >= m, choose m from n; */ // private int cmn(long n, long m) { // if (m > n) { // n ^= m; // m ^= n; // n ^= m; // } // m = Math.min(m, n - m); // // long top = 1; // long bot = 1; // for (long i = n - m + 1; i <= n; i++) { // top = (top * i) % MOD; // } // for (int i = 1; i <= m; i++) { // bot = (bot * i) % MOD; // } // // return (int) ((top * pow(bot, MOD - 2, MOD)) % MOD); // } long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b != 0) { long tmp = a % b; a = b; b = tmp; } return a; } int[] unique(int a[], Map<Integer, Integer> idx, Map<Integer, Integer> cnt) { Integer order[] = new Integer[a.length]; for (int i = 0; i < a.length; i++) { order[i] = i; } Arrays.sort(order, Comparator.comparingInt(o -> a[o])); int tmp[] = new int[a.length]; for (int i = 0; i < a.length; i++) { tmp[i] = a[order[i]]; } int j = 0; for (int i = 0; i < tmp.length; i++) { if (i == 0 || tmp[i] > tmp[i - 1]) { idx.put(tmp[i], j++); } cnt.put(idx.get(tmp[i]), cnt.getOrDefault(idx.get(tmp[i]), 0) + 1); } int rs[] = new int[j]; j = 0; for (int key : idx.keySet()) { rs[j++] = key; } Arrays.sort(rs); return rs; } boolean isEven(long n) { return (n & 1) == 0; } static class BinSearch { static long bs(long l, long r, IBinSearch sort) throws IOException { while (l < r) { long m = l + (r - l) / 2; if (sort.binSearchCmp(m)) { l = m + 1; } else { r = m; } } return l; } interface IBinSearch { boolean binSearchCmp(long k) throws IOException; } } } private static class InOut { private BufferedReader br; private StreamTokenizer st; private PrintWriter pw; InOut() throws FileNotFoundException { if (useInFile) { System.setIn(new FileInputStream("resources/inout/in.text")); } if (useOutFile) { System.setOut(new PrintStream("resources/inout/out.text")); } br = new BufferedReader(new InputStreamReader(System.in)); st = new StreamTokenizer(br); pw = new PrintWriter(new OutputStreamWriter(System.out)); st.ordinaryChar('\''); st.ordinaryChar('\"'); st.ordinaryChar('/'); } private long[] anLong(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } private String next() throws IOException { st.nextToken(); return st.sval; } private String next(int len) throws IOException { char ch[] = new char[len]; int cur = 0; char c; while ((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t') ; do { ch[cur++] = c; } while (!((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t')); return String.valueOf(ch, 0, cur); } private int nextInt() throws IOException { st.nextToken(); return (int) st.nval; } private long nextLong(int n) throws IOException { return Long.parseLong(next(n)); } private double nextDouble() throws IOException { st.nextToken(); return st.nval; } private String[] nextSS(String reg) throws IOException { return br.readLine().split(reg); } private String nextLine() throws IOException { return br.readLine(); } private void print(String s, boolean newLine) { if (null != s) { pw.print(s); } if (newLine) { pw.println(); } } private void format(String format, Object... obj) { pw.format(format, obj); } private void flush() { pw.flush(); } } private static class FFT { double[] roots; int maxN; public FFT(int maxN) { this.maxN = maxN; initRoots(); } public long[] multiply(int[] a, int[] b) { int minSize = a.length + b.length - 1; int bits = 1; while (1 << bits < minSize) bits++; int N = 1 << bits; double[] aa = toComplex(a, N); double[] bb = toComplex(b, N); fftIterative(aa, false); fftIterative(bb, false); double[] c = new double[aa.length]; for (int i = 0; i < N; i++) { c[2 * i] = aa[2 * i] * bb[2 * i] - aa[2 * i + 1] * bb[2 * i + 1]; c[2 * i + 1] = aa[2 * i] * bb[2 * i + 1] + aa[2 * i + 1] * bb[2 * i]; } fftIterative(c, true); long[] ret = new long[minSize]; for (int i = 0; i < ret.length; i++) { ret[i] = Math.round(c[2 * i]); } return ret; } static double[] toComplex(int[] arr, int size) { double[] ret = new double[size * 2]; for (int i = 0; i < arr.length; i++) { ret[2 * i] = arr[i]; } return ret; } void initRoots() { roots = new double[2 * (maxN + 1)]; double ang = 2 * Math.PI / maxN; for (int i = 0; i <= maxN; i++) { roots[2 * i] = Math.cos(i * ang); roots[2 * i + 1] = Math.sin(i * ang); } } int bits(int N) { int ret = 0; while (1 << ret < N) ret++; if (1 << ret != N) throw new RuntimeException(); return ret; } void fftIterative(double[] array, boolean inv) { int bits = bits(array.length / 2); int N = 1 << bits; for (int from = 0; from < N; from++) { int to = Integer.reverse(from) >>> (32 - bits); if (from < to) { double tmpR = array[2 * from]; double tmpI = array[2 * from + 1]; array[2 * from] = array[2 * to]; array[2 * from + 1] = array[2 * to + 1]; array[2 * to] = tmpR; array[2 * to + 1] = tmpI; } } for (int n = 2; n <= N; n *= 2) { int delta = 2 * maxN / n; for (int from = 0; from < N; from += n) { int rootIdx = inv ? 2 * maxN : 0; double tmpR, tmpI; for (int arrIdx = 2 * from; arrIdx < 2 * from + n; arrIdx += 2) { tmpR = array[arrIdx + n] * roots[rootIdx] - array[arrIdx + n + 1] * roots[rootIdx + 1]; tmpI = array[arrIdx + n] * roots[rootIdx + 1] + array[arrIdx + n + 1] * roots[rootIdx]; array[arrIdx + n] = array[arrIdx] - tmpR; array[arrIdx + n + 1] = array[arrIdx + 1] - tmpI; array[arrIdx] += tmpR; array[arrIdx + 1] += tmpI; rootIdx += (inv ? -delta : delta); } } } if (inv) { for (int i = 0; i < array.length; i++) { array[i] /= N; } } } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
55a58152233a4807e9c50b7082249daf
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
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.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static void main(String[] args) { try { FastReader in = new FastReader(); FastWriter out = new FastWriter(); int testCases = in.nextInt(); StringBuilder sb = new StringBuilder(); while (testCases-- > 0) { int n = in.nextInt(); int k = in.nextInt(); List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n + 1; i++) { adj.add(new ArrayList<>()); } for (int i = 2; i <= n; i++) { int par = in.nextInt(); adj.get(par).add(i); } sb.append(fun(n, k, adj) + "\n"); } out.print(sb); out.close(); } catch (Exception e) { return; } } static int fun(int n, int k, List<List<Integer>> adj) { int low = 2; int high = n; while (low < high) { int mid = (low + high) / 2; if (poss(1, new int[] { k }, adj, mid) != -1) { high = mid; } else { low = mid + 1; } } return high - 1; } static int poss(int node, int[] k, List<List<Integer>> adj, int h) { int dep = 1; for (int a : adj.get(node)) { int d = poss(a, k, adj, h); if (d == -1) { return -1; } if (d == h - 1 && node != 1) { if (k[0] == 0) { return -1; } k[0]--; d = 0; } if (d == h && node == 1) { return -1; } d++; dep = Math.max(dep, d); } return dep; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
7f49d3985ddd64ddf8f0516f7bda69d6
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class Solution { static Scanner sc = new Scanner(System.in); 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) { // out.append("Case #" + tc + ": "); Solution run = new Solution(); run.run(); } System.out.println(out); } static ArrayList<Integer> gr[]; static class sort { String c; int u; int d; int id; public sort(String s, int u, int val) { c = s; this.u = u; this.d = val; } } public void run() throws IOException { int n=sc.nextInt(); int k=sc.nextInt(); gr = new ArrayList[n+1]; for(int i=0;i<=n;i++) { gr[i]=new ArrayList<>(); } for(int i=2;i<=n;i++) { int u=sc.nextInt(); gr[u].add(i); } int lo=1,hi= n-1; int ans = (int)1e9; while(lo<=hi) { int mid=(lo+hi)/2; int val[] = dfs(1,mid,1); if(val[0]<=k) { ans= mid; hi=mid-1; } else lo=mid+1; } out.append(ans+"\n"); } static int[] dfs(int root, int k, int pa) { int ans[] = {0,0}; for(int ch: gr[root]) { int val [] = dfs(ch,k, root); ans[0]+= val[0]; ans [1]= Math.max(ans[1], val[1]); } ans[1]++; if(pa != 1 && ans[1]==k) { ans[0]++; ans[1]=0; } return ans; } static int getParent(int x, int par[]) { if (x == par[x]) return x; par[x] = getParent(par[par[x]], par); return par[x]; } 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
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
088273522592989fdf679fae561e933b
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class CF1{ public static void main(String[] args) { FastScanner sc=new FastScanner(); // hamare saath shree raghunath to kis baat ki chinta... int T=sc.nextInt(); // int T=1; for (int tt=1; tt<=T; tt++){ int n = sc.nextInt(); int k = sc.nextInt(); ArrayList<Integer> graph[]= new ArrayList[n+1]; for (int i=1; i<=n; i++) graph[i]= new ArrayList<>(); int arr[]= new int [n+1]; for (int i=2; i<=n; i++){ int yy= sc.nextInt(); graph[yy].add(i); arr[i]=yy; } if (n==1){ System.out.println(0); continue; } arr[1]=1; Pair depth[]= new Pair[n+1]; dfs(0,1,graph,depth); depth[0]= new Pair(1,1); depth[1]=new Pair(1,1); Arrays.sort(depth); int ans=depth[0].x; int lo=1; int hi=n-1; while (lo<=hi){ int mid= (lo+hi)/2; int x[]= arr.clone(); int tempans=0; for (Pair temp: depth){ if (mid>=temp.x) continue; int z=temp.y; int d=1; while (x[z]!=z){ int u=x[z]; x[z]=z; z=u; if (d>=mid) {tempans++; break;} d++; } } if (tempans>k) lo=mid+1; else { hi=mid-1; ans=mid; } } System.out.println(ans); } } static void dfs(int dep, int node, ArrayList<Integer> graph[], Pair depth[]){ depth[node]= new Pair(dep, node); for (int c: graph[node]) dfs(dep+1, c,graph,depth); } static long prime(long n){ for (long i=3; i*i<=n; i+=2){ if (n%i==0) return i; } return -1; } static long factorial (int x){ if (x==0) return 1; long ans =x; for (int i=x-1; i>=1; i--){ ans*=i; ans%=mod; } return ans; } static boolean killMePls = false; // public static void main(String[] args) throws Exception { // Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { // public void uncaughtException(Thread t, Throwable e) {killMePls = true;} // }; // Thread t = new Thread(null, ()->A(args), "", 1<<28); // t.setUncaughtExceptionHandler(h); // t.start(); // t.join(); // if(killMePls) throw null; // } static int mod2= 998244353; static long mod=1000000007L; static long power2 (long a, long b){ long res=1; while (b>0){ if ((b&1)== 1){ res= (res * a % mod)%mod; } a=(a%mod * a%mod)%mod; b=b>>1; } return res; } static void sort(int[] a){ ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sortLong(long[] a){ ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static long gcd (long n, long m){ if (m==0) return n; else return gcd(m, n%m); } static class Pair implements Comparable<Pair>{ int x, y; private static final int hashMultiplier = BigInteger.valueOf(new Random().nextInt(1000) + 100).nextProbablePrime().intValue(); public Pair(int x, int y){ this.x = x; this.y = y; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pii = (Pair) o; if (x != pii.x) return false; return y == pii.y; } public int hashCode() { return hashMultiplier * x + y; } public int compareTo(Pair o){ if (this.x==o.x) return Integer.compare(this.y,o.y); else return Integer.compare(o.x,this.x); } // this.x-o.x is ascending } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 8
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
85dc31d8ad31d089703b6f684e5343fa
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
//Utilities import java.io.*; import java.util.*; public class a { static int t; static int n, k; static HashSet<Integer>[] adj; static int[] p, deg; static int res; public static void main(String[] args) throws IOException { t = in.iscan(); outer : while (t-- > 0) { n = in.iscan(); k = in.iscan(); adj = new HashSet[n+1]; for (int i = 0; i <= n; i++) { adj[i] = new HashSet<Integer>(); } p = new int[n+1]; deg = new int[n+1]; for (int i = 2; i <= n; i++) { p[i] = in.iscan(); adj[i].add(p[i]); adj[p[i]].add(i); deg[i]++; deg[p[i]]++; } int l = 1, r = n-1, mid; while (l <= r) { mid = (l+r)/2; if (works(mid)) { res = mid; r = mid-1; } else { l = mid+1; } } out.println(res); } out.close(); } static int cnt; static boolean works(int maxH) { cnt = 0; dfs(1, -1, maxH); return cnt <= k; } static int dfs(int idx, int prev, int maxH) { int h = 0; for (int u : adj[idx]) { if (u != prev) { h = Math.max(h, 1 + dfs(u, idx, maxH)); } } if (idx != 1 && p[idx] != 1 && h+1 == maxH) { cnt++; h = -1; } return h; } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static void sort(int[] a, boolean increasing) { ArrayList<Integer> arr = new ArrayList<Integer>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(long[] a, boolean increasing) { ArrayList<Long> arr = new ArrayList<Long>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(double[] a, boolean increasing) { ArrayList<Double> arr = new ArrayList<Double>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static void updateMap(HashMap<Integer, Integer> map, int key, int v) { if (!map.containsKey(key)) { map.put(key, v); } else { map.put(key, map.get(key) + v); } if (map.get(key) == 0) { map.remove(key); } } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static long fast_pow (long b, long x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { if (k > n) { return 0; } k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } // start of permutation and lower/upper bound template public static void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } public static void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } public static void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } static int lower_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= cmp) high = mid; else low = mid + 1; } return low; } static int upper_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > cmp) high = mid; else low = mid + 1; } return low; } // end of permutation and lower/upper bound template } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
5af8066b10dd2c498b4230f738c6ac89
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) { new MainClass().execute(); } } class MainClass extends PrintWriter { MainClass() { super(System.out, true); } boolean cases = true; // Solution List<Integer>[] al; int n; int dep; void solveIt(int testCaseNo) { this.n = sc.nextInt(); int k = sc.nextInt(); int a[] = sc.readIntArray(n - 1); this.al = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { al[i] = new ArrayList<>(); } for (int i = 0; i < a.length; i++) { al[i + 2].add(a[i]); al[a[i]].add(i + 2); } int s = 1, e = n; int ans = -1; while (s <= e) { int mid = s + (e - s) / 2; if (ok(mid, k)) { e = mid - 1; ans = mid; } else { s = mid + 1; } } println(ans); } int x = 0; boolean ok(int len, int k) { this.x = 0; dfs(1, -1, len); return x <= k; } int dfs(int node, int par, int len) { int d = 1; for (int next : al[node]) { if (next == par) continue; d = max(d, dfs(next, node, len) + 1); } if (d == len && par != 1 && node != 1) { x++; return 0; } return d; } void solve() { int caseNo = 1; if (cases) for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); } solveIt(caseNo); } void execute() { long S = System.currentTimeMillis(); is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); this.sc = new FastIO(); solve(); out.flush(); long G = System.currentTimeMillis(); sc.tr(G - S + "ms"); } class FastIO { private boolean endOfFile() { if (bufferLength == -1) return true; int lptr = ptrbuf; while (lptr < bufferLength) { // _|_ if (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++])) return false; } try { is.mark(1000); while (true) { int b = is.read(); if (b == -1) { is.reset(); return true; } else if (!isThisTheSpaceCharacter(b)) { is.reset(); return false; } } } catch (IOException e) { return true; } } private byte[] inputBufffferBigBoi = new byte[1024]; int bufferLength = 0, ptrbuf = 0; private int justReadTheByte() { if (bufferLength == -1) throw new InputMismatchException(); if (ptrbuf >= bufferLength) { ptrbuf = 0; try { bufferLength = is.read(inputBufffferBigBoi); } catch (IOException e) { throw new InputMismatchException(); } if (bufferLength <= 0) return -1; } return inputBufffferBigBoi[ptrbuf++]; } private boolean isThisTheSpaceCharacter(int c) { return !(c >= 33 && c <= 126); } private int skipItBishhhhhhh() { int b; while ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b)); return b; } private double nextDouble() { return Double.parseDouble(next()); } private char nextChar() { return (char) skipItBishhhhhhh(); } private String next() { int b = skipItBishhhhhhh(); StringBuilder sb = new StringBuilder(); while (!(isThisTheSpaceCharacter(b))) { sb.appendCodePoint(b); b = justReadTheByte(); } return sb.toString(); } private char[] readCharArray(int n) { char[] buf = new char[n]; int b = skipItBishhhhhhh(), p = 0; while (p < n && !(isThisTheSpaceCharacter(b))) { buf[p++] = (char) b; b = justReadTheByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] readCharMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = readCharArray(m); return map; } private int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } private long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } private int nextInt() { int num = 0, b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private long nextLong() { long num = 0; int b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private void tr(Object... o) { if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o)); } } InputStream is; PrintWriter out; String INPUT = ""; final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; final long mod = (long) 1e9 + 7; FastIO sc; } // And I wish you could sing along, But this song is a joke, and the melody I // wrote, wrong
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
eb9a34609ae64f406119392e11aef8d8
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) { new MainClass().execute(); } } class MainClass extends PrintWriter { MainClass() { super(System.out, true); } boolean cases = true; // Solution List<Integer>[] al; int n; int dep; void solveIt(int testCaseNo) { this.n = sc.nextInt(); int k = sc.nextInt(); int a[] = sc.readIntArray(n - 1); this.al = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { al[i] = new ArrayList<>(); } for (int i = 0; i < a.length; i++) { al[i + 2].add(a[i]); al[a[i]].add(i + 2); } int s = 1, e = n; int ans = -1; while (s <= e) { int mid = s + (e - s) / 2; if (ok(mid, k)) { e = mid - 1; ans = mid; } else { s = mid + 1; } } println(ans); } int x = 0; boolean ok(int len, int k) { this.x = 0; dfs(1, -1, len); return x <= k; } int dfs(int node, int par, int len) { int d = 1; for (int next : al[node]) { if (next != par) { d = max(d, dfs(next, node, len) + 1); } } if (d == len && par != 1 && node != 1) { x++; return 0; } return d; } void solve() { int caseNo = 1; if (cases) for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); } solveIt(caseNo); } void execute() { long S = System.currentTimeMillis(); is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); this.sc = new FastIO(); solve(); out.flush(); long G = System.currentTimeMillis(); sc.tr(G - S + "ms"); } class FastIO { private boolean endOfFile() { if (bufferLength == -1) return true; int lptr = ptrbuf; while (lptr < bufferLength) { // _|_ if (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++])) return false; } try { is.mark(1000); while (true) { int b = is.read(); if (b == -1) { is.reset(); return true; } else if (!isThisTheSpaceCharacter(b)) { is.reset(); return false; } } } catch (IOException e) { return true; } } private byte[] inputBufffferBigBoi = new byte[1024]; int bufferLength = 0, ptrbuf = 0; private int justReadTheByte() { if (bufferLength == -1) throw new InputMismatchException(); if (ptrbuf >= bufferLength) { ptrbuf = 0; try { bufferLength = is.read(inputBufffferBigBoi); } catch (IOException e) { throw new InputMismatchException(); } if (bufferLength <= 0) return -1; } return inputBufffferBigBoi[ptrbuf++]; } private boolean isThisTheSpaceCharacter(int c) { return !(c >= 33 && c <= 126); } private int skipItBishhhhhhh() { int b; while ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b)); return b; } private double nextDouble() { return Double.parseDouble(next()); } private char nextChar() { return (char) skipItBishhhhhhh(); } private String next() { int b = skipItBishhhhhhh(); StringBuilder sb = new StringBuilder(); while (!(isThisTheSpaceCharacter(b))) { sb.appendCodePoint(b); b = justReadTheByte(); } return sb.toString(); } private char[] readCharArray(int n) { char[] buf = new char[n]; int b = skipItBishhhhhhh(), p = 0; while (p < n && !(isThisTheSpaceCharacter(b))) { buf[p++] = (char) b; b = justReadTheByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] readCharMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = readCharArray(m); return map; } private int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } private long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } private int nextInt() { int num = 0, b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private long nextLong() { long num = 0; int b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private void tr(Object... o) { if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o)); } } InputStream is; PrintWriter out; String INPUT = ""; final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; final long mod = (long) 1e9 + 7; FastIO sc; } // And I wish you could sing along, But this song is a joke, and the melody I // wrote, wrong
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
217e5e922cfdf518bd952ebdfb76e77e
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import static java.lang.Math.*; public class D { public Object solve () { int N = sc.nextInt(), K = sc.nextInt(); int [] P = dec(sc.nextInts()); int [][] E = new int [N-1][]; for (int i : rep(N-1)) E[i] = new int [] { P[i], i+1 }; G = dgraph(N, E); H = new boolean [N]; H[0] = true; for (int i : G[0]) H[i] = true; int p = 0, q = N; while (q - p > 1) { int m = (p + q) / 2; int c = dfs(0, m)[0]; if (c <= K) q = m; else p = m; } return q; } int [][] G; boolean [] H; int [] dfs (int i, int m) { int c = 0, d = 1; for (int j : G[i]) { int [] r = dfs(j, m); c += r[0]; d = max(d, 1 + r[1]); } if (!H[i] && d >= m) { d = 0; ++c; } int [] res = { c, d }; return res; } private static final int CONTEST_TYPE = 2; private static void init () { } private static int [] dec (int ... A) { for (int i = 0; i < A.length; ++i) --A[i]; return A; } private static int [][] dgraph (int N, int [][] E) { return dwgraph(N, E)[0]; } private static int [][][] dwgraph (int N, int [][] E) { int [] D = new int [N]; for (int [] e : E) ++D[e[0]]; int [][][] res = new int [2][N][]; for (int i = 0; i < 2; ++i) for (int j = 0; j < N; ++j) res[i][j] = new int [D[j]]; D = new int [N]; for (int [] e : E) { int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1; res[0][x][D[x]] = y; res[1][x][D[x]] = z; ++D[x]; } return res; } private static int [] rep (int N) { return rep(0, N); } private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static class IOUtils { public static class MyScanner { public String next () { newLine(); return line[index++]; } public int nextInt () { return Integer.parseInt(next()); } public String nextLine () { line = null; return readLine(); } public String [] nextStrings () { return split(nextLine()); } public int [] nextInts () { String [] S = nextStrings(); int N = S.length; int [] res = new int [N]; for (int i = 0; i < N; ++i) res[i] = Integer.parseInt(S[i]); return res; } ////////////////////////////////////////////// private boolean eol () { return index == line.length; } private String readLine () { try { int b; StringBuilder res = new StringBuilder(); while ((b = System.in.read()) < ' ') continue; res.append((char)b); while ((b = System.in.read()) >= ' ') res.append((char)b); return res.toString(); } catch (Exception e) { throw new Error (e); } } private MyScanner () { try { while (System.in.available() == 0) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine () { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim (String delim, Object o, Object ... A) { java.util.List<String> str = new java.util.ArrayList<>(); append(str, o); for (Object p : A) append(str, p); return String.join(delim, str.toArray(new String [0])); } ////////////////////////////////////////////////////////////////////////////////// private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start () { if (t == 0) t = millis(); } private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append (java.util.List<String> str, Object o) { append(x -> append(str, x), x -> str.add(x.toString()), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void flush () { pw.flush(); System.out.flush(); } private static void print (Object o, Object ... A) { String res = build(o, A); if (DEBUG == 0) { String out = res.split(System.lineSeparator())[0]; if (out.length() > 80) out = out.substring(0, 80); if (out.length() < res.length()) out += " ..."; err(out, '(', time(), ')'); } if (DEBUG == 2) err(res, '(', time(), ')'); if (res.length() > 0) pw.println(res); if (DEBUG == 1) flush(); } private static void err (Object o, Object ... A) { System.err.println(build(o, A)); } private static int DEBUG; private static void exit () { String end = "------------------" + System.lineSeparator() + time(); switch(DEBUG) { case 1: print(end); break; case 0: case 2: err(end); break; } IOUtils.pw.close(); System.out.flush(); System.exit(0); } private static long t; private static long millis () { return System.currentTimeMillis(); } private static String time () { return "Time: " + (millis() - t) / 1000.0; } private static void run (int N) { try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new D().solve(); if (res != null) { @SuppressWarnings("all") Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res; print(o); } } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { @SuppressWarnings("all") int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt(); init(); IOUtils.run(N); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
06585f0fa8e5b5c364f6b70d177e87b5
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import static java.lang.Math.*; public class D { public Object solve () { int N = sc.nextInt(), K = sc.nextInt(); int [] P = dec(sc.nextInts()); int [][] E = new int [N-1][]; for (int i : rep(N-1)) E[i] = new int [] { P[i], i+1 }; G = dgraph(N, E); H = new boolean [N]; H[0] = true; for (int i : G[0]) H[i] = true; D = new int [N]; dfs(0); int p = 0, q = N; while (q - p > 1) { int m = (p + q) / 2; int c = dfs(0, m, new int [N]); if (c <= K) q = m; else p = m; } return q; } int [][] G; int [] D; boolean [] H; int dfs(int i) { int res = 1; for (int j : G[i]) res = max(res, 1 + dfs(j)); return D[i] = res; } int dfs(int i, int m, int [] D) { int res = 0; D[i] = 1; for (int j : G[i]) { res += dfs(j, m, D); D[i] = max(D[i], 1 + D[j]); } if (!H[i] && D[i] >= m) { D[i] = 0; ++res; } return res; } private static final int CONTEST_TYPE = 2; private static void init () { } private static int [] dec (int ... A) { for (int i = 0; i < A.length; ++i) --A[i]; return A; } private static int [][] dgraph (int N, int [][] E) { return dwgraph(N, E)[0]; } private static int [][][] dwgraph (int N, int [][] E) { int [] D = new int [N]; for (int [] e : E) ++D[e[0]]; int [][][] res = new int [2][N][]; for (int i = 0; i < 2; ++i) for (int j = 0; j < N; ++j) res[i][j] = new int [D[j]]; D = new int [N]; for (int [] e : E) { int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1; res[0][x][D[x]] = y; res[1][x][D[x]] = z; ++D[x]; } return res; } private static int [] rep (int N) { return rep(0, N); } private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static class IOUtils { public static class MyScanner { public String next () { newLine(); return line[index++]; } public int nextInt () { return Integer.parseInt(next()); } public String nextLine () { line = null; return readLine(); } public String [] nextStrings () { return split(nextLine()); } public int [] nextInts () { String [] S = nextStrings(); int N = S.length; int [] res = new int [N]; for (int i = 0; i < N; ++i) res[i] = Integer.parseInt(S[i]); return res; } ////////////////////////////////////////////// private boolean eol () { return index == line.length; } private String readLine () { try { int b; StringBuilder res = new StringBuilder(); while ((b = System.in.read()) < ' ') continue; res.append((char)b); while ((b = System.in.read()) >= ' ') res.append((char)b); return res.toString(); } catch (Exception e) { throw new Error (e); } } private MyScanner () { try { while (System.in.available() == 0) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine () { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim (String delim, Object o, Object ... A) { java.util.List<String> str = new java.util.ArrayList<>(); append(str, o); for (Object p : A) append(str, p); return String.join(delim, str.toArray(new String [0])); } ////////////////////////////////////////////////////////////////////////////////// private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start () { if (t == 0) t = millis(); } private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append (java.util.List<String> str, Object o) { append(x -> append(str, x), x -> str.add(x.toString()), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void flush () { pw.flush(); System.out.flush(); } private static void print (Object o, Object ... A) { String res = build(o, A); if (DEBUG == 0) { String out = res.split(System.lineSeparator())[0]; if (out.length() > 80) out = out.substring(0, 80); if (out.length() < res.length()) out += " ..."; err(out, '(', time(), ')'); } if (DEBUG == 2) err(res, '(', time(), ')'); if (res.length() > 0) pw.println(res); if (DEBUG == 1) flush(); } private static void err (Object o, Object ... A) { System.err.println(build(o, A)); } private static int DEBUG; private static void exit () { String end = "------------------" + System.lineSeparator() + time(); switch(DEBUG) { case 1: print(end); break; case 0: case 2: err(end); break; } IOUtils.pw.close(); System.out.flush(); System.exit(0); } private static long t; private static long millis () { return System.currentTimeMillis(); } private static String time () { return "Time: " + (millis() - t) / 1000.0; } private static void run (int N) { try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new D().solve(); if (res != null) { @SuppressWarnings("all") Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res; print(o); } } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { @SuppressWarnings("all") int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt(); init(); IOUtils.run(N); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
7f9be1ce9084d6547a9f23825df5e12a
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.function.Predicate; public class E1739D { static int n; static ArrayList<Integer>[] adj; static int k; static int allowedK; static int[] dep; public static void main(String[] args) { FastIO io = new FastIO(); int t = io.nextInt(); while (t-- > 0) { n = io.nextInt(); allowedK = io.nextInt(); adj = new ArrayList[n]; dep = new int[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); for (int i = 1; i < n; i++) adj[io.nextInt() - 1].add(i); int ans = firstTrue(1, n, x -> ok(x)); io.println(ans); } io.close(); } private static int firstTrue(int lo, int hi, Predicate<Integer> test) { hi++; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (test.test(mid)) { hi = mid; } else { lo = mid + 1; } } return lo; } static boolean ok(int m) { dep = new int[n]; k = 0; dfs(0, 0, m); return k <= allowedK; } static void dfs(int s, int p, int m) { for (int v : adj[s]) { dfs(v, s, m); dep[s] = Math.max(dep[s], dep[v] + 1); } if (dep[s] == m - 1 && p != 0) { k++; dep[s] = -1; } } private static class FastIO extends PrintWriter { private final InputStream stream; private final 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 long nextLong() { // nextLong() would be implemented similarly 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; } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
d16ceee62d9b709a865ce85953618e2c
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } int[] na(int n) throws IOException { int[]A=new int[n]; for (int i=0;i<n;i++) A[i]=ni(); return A; } long mod=1000000007; ArrayList<Integer>[]A,H; int[]P; boolean[]F; int maxh; void solve() throws IOException { for (int tc=ni();tc>0;tc--) { int n=ni(),k=ni(); A=new ArrayList[n+1]; for (int i=1;i<=n;i++) A[i]=new ArrayList(); P=new int[n+1]; for (int i=2;i<=n;i++) { P[i]=ni(); A[P[i]].add(i); } H=new ArrayList[n+1]; for (int i=0;i<=n;i++) H[i]=new ArrayList(); maxh=0; dfs1(1,0); if (n-1-A[1].size()<=k) { out.println(1); continue; } int lt=1; int rt=maxh; F=new boolean[n+1]; while (lt+1<rt) { int av=(lt+rt)/2; Arrays.fill(F,false); int ct=0; for (int i=maxh;i>av;i--) { for (int u:H[i]) { if (F[u]) continue; ct++; int p=u; for (int j=1;j<av;j++) p=P[p]; dfs2(p); } } if (ct<=k) rt=av; else lt=av; } out.println(rt); } out.flush(); } void dfs2(int u) { if (F[u]) return; F[u]=true; for (int v:A[u]) dfs2(v); } void dfs1(int u,int h) { H[h].add(u); maxh=Math.max(maxh,h); for (int v:A[u]) dfs1(v,h+1); } int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); } long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); } long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; } public static void main(String[] args) throws IOException { new Main().solve(); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
cb81110f2f6c7d716403abcd02bd0ccd
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; public class ComdeFormces { static int x[]= {-1,0,0,1,1,1,-1,-1}; static int y[]= {0,1,-1,0,1,-1,1,-1}; static int dp[][][][]; static int seg[]; static class Trie{ Trie a[]; int ind; public Trie() { this.a=new Trie[3]; this.ind=-1; } } static long ncr[][]; static int cnt; public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub FastReader sc=new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); // OutputStream out = new BufferedOutputStream ( System.out ); int t=sc.nextInt(); int tc=1; while(t--!=0) { int n=sc.nextInt(); int k=sc.nextInt(); int a[]=new int[n-1]; for(int i=0;i<n-1;i++)a[i]=sc.nextInt(); ArrayList<ArrayList<Integer>> ar=new ArrayList<>(); for(int i=0;i<n;i++)ar.add(new ArrayList<>()); for(int i=0;i<n-1;i++) { ar.get(a[i]-1).add(i+1); ar.get(i+1).add(a[i]-1); } int s=2; int e=n; while(s<=e) { int m=s+(e-s)/2; cnt=0; int ht=eval(ar,m,0,-1); if(cnt<=k && ht<=m)e=m-1; else s=m+1; } log.write((s-1)+"\n"); log.flush(); } } static int eval(ArrayList<ArrayList<Integer>> ar,int h,int src,int pr) { // int cnt=0; int mx=0; for(int k:ar.get(src)) { if(k==pr)continue; int ht=eval(ar,h,k,src); if(ht<h-1) { mx=Math.max(mx, ht); } else if(ht==h-1 && src!=0)cnt++; } return mx+1; } static void insert(Trie proot,int a[],int ind) { Trie root=proot; for(int i=0;i<a.length;i++) { if(root.a[a[i]]==null) { root.a[a[i]]=new Trie(); root=root.a[a[i]]; } else root=root.a[a[i]]; } root.ind=ind; } static int ser(Trie proot,int a[],int b[]) { Trie root=proot; for(int i=0;i<a.length;i++) { if(a[i]==b[i]) { if(root.a[a[i]]==null)return -1; root=root.a[a[i]]; } else { if((a[i]==1 || a[i]==0) && (b[i]==0 || b[i]==1)) { if(root.a[2]==null)return -1; root=root.a[2]; } else if((a[i]==1 || a[i]==2) && (b[i]==1 || b[i]==2)) { if(root.a[0]==null)return -1; root=root.a[0]; } else if((a[i]==2 || a[i]==0) && (b[i]==2 || b[i]==0)) { if(root.a[1]==null)return -1; root=root.a[1]; } } } return root.ind; } public static int m=(int)(998244353); public static int mul(int a, int b) { return ((a%m)*(b%m))%m; } public static long mul(long a, long b) { return ((a%m)*(b%m))%m; } public static int add(int a, int b) { return ((a%m)+(b%m))%m; } public static long add(long a, long b) { return ((a%m)+(b%m))%m; } public static long sub(long a,long b) { return ((a%m)-(b%m)+m)%m; } static long gcd(long a,long b) { if(b==0)return a; else return gcd(b,a%b); } static int gcd(int a,int b) { if(b==0)return a; else return gcd(b,a%b); } static long ncr(int n, int r){ if(r>n-r)r=n-r; long ans=1; long m=998244353; for(int i=0;i<r;i++){ ans=mul(ans,(n-i)); ans=div(ans,i+1,m); } return ans; } public static class num{ long v; } static long gcd(long a,long b,num x,num y) { if(b==0) { x.v=1; y.v=0; return a; } num x1=new num(); num y1=new num(); long ans=gcd(b,a%b,x1,y1); x.v=y1.v; y.v=x1.v-(a/b)*y1.v; return ans; } static long inverse(long b,long m) { num x=new num(); num y=new num(); long gc=gcd(b,m,x,y); if(gc!=1) { return -1; } return (x.v%m+m)%m; } static long div(long a,long b,long m) { a%=m; if(inverse(b,m)==-1)return a/b; return (inverse(b,m)*a)%m; } public static class trip{ int a; int b; int c; public trip(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } } static void mergesort(int[] a,int start,int end) { if(start>=end)return ; int mid=start+(end-start)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } static void merge(int[] a, int start,int mid,int end) { int ptr1=start; int ptr2=mid+1; int b[]=new int[end-start+1]; int i=0; while(ptr1<=mid && ptr2<=end) { if(a[ptr1]<=a[ptr2]) { b[i]=a[ptr1]; ptr1++; i++; } else { b[i]=a[ptr2]; ptr2++; i++; } } while(ptr1<=mid) { b[i]=a[ptr1]; ptr1++; i++; } while(ptr2<=end) { b[i]=a[ptr2]; ptr2++; i++; } for(int j=start;j<=end;j++) { a[j]=b[j-start]; } } public static class FastReader { BufferedReader b; StringTokenizer s; public FastReader() { b=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(s==null ||!s.hasMoreElements()) { try { s=new StringTokenizer(b.readLine()); } catch(IOException e) { e.printStackTrace(); } } return s.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=b.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } boolean hasNext() { if (s != null && s.hasMoreTokens()) { return true; } String tmp; try { b.mark(1000); tmp = b.readLine(); if (tmp == null) { return false; } b.reset(); } catch (IOException e) { return false; } return true; } } public static class pair{ int a; int b; public pair(int a,int b) { this.a=a; this.b=b; } @Override public String toString() { return "{"+this.a+" "+this.b+"}"; } } static long pow(long a, long pw) { long temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } public static int md=998244353; static int pow(int a, int pw) { int temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
bd4f4fd802980400426884206d2fa282
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; public class Main { static int t; static Vector<Vector<Integer>> a = new Vector<Vector<Integer>>(); static Scanner scanner = new Scanner(System.in); static Pair dfs(int u, int p, int m){ Pair res = new Pair(1, 0); for(int v: a.get(u)){ Pair val = dfs(v, u, m); res.first = Math.max(res.first, val.first + 1); res.second += val.second; } if(u == 1) return res; if(p != 1){ if(res.first >= m){ res.first = 0; res.second += 1; } } else{ if(res.first > m){ res.first = 0; res.second += 1; } } return res; } static void solve(){ int n = scanner.nextInt(); int k = scanner.nextInt(); a.clear(); for(int i = 1; i <= n + 5; i++){ Vector<Integer> x = new Vector<>(); a.add(x); } for(int i = 2; i <= n; i++){ int p = scanner.nextInt(); a.get(p).add(i); } int res = n - 1; int l = 1, r = n - 1; while(l <= r){ int m = (l + r) / 2; int cnt = 0; Pair val = dfs(1, 1, m); if(val.second <= k){ res = m; r = m - 1; } else{ l = m + 1; } } System.out.println(res); } public static void main(String[] args) { int t = scanner.nextInt(); while(t-- > 0) solve(); } static class Pair{ int first, second; public Pair() { } public Pair(int first, int second) { this.first = first; this.second = second; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
880fae05e10acc047e0d6969f0d4f33b
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class D { static IOHandler sc = new IOHandler(); static List<Integer> [] graph; static int [] depth; public static void main(String[] args) { // TODO Auto-generated method stub int testCases = sc.nextInt(); for (int i = 1; i <= testCases; ++i) { solve(i); } } private static void solve(int t) { int n = sc.nextInt(); int k = sc.nextInt(); graph = new List[n + 1]; depth = new int [n + 1]; for (int i = 1; i <= n; ++i) { graph[i] = new ArrayList<>(); } int [] parents; parents = new int [n + 1]; for (int i = 2; i <= n; ++i) { parents[i] = sc.nextInt(); graph[parents[i]].add(i); } dfs(1, 0, 0); int max = 1; for (int num : depth) { max = Math.max(max, num); } int min = 0; int mid; int count; int num; while (max - min > 1) { mid = (max + min) / 2; count = 0; //System.out.println(mid + " " + count); if (solve3(n, 0, mid, parents) <= k) max = mid; else min = mid; } System.out.println(max); } private static int solve3(int n, int depth, int maxL, int [] parents) { Queue<int []> queue = new LinkedList<>(); int [] counts = new int [n + 1]; int [] maxDepth = new int [n + 1]; counts[1] = graph[1].size(); for (int i = 2; i <= n; ++i) { counts[i] = graph[i].size(); } boolean [] visited = new boolean [n + 1]; for (int i = 2; i <= n; ++i) { if (graph[i].size() == 0) { queue.add(new int [] {i , 0}); } } //System.out.println(Arrays.toString(counts)); int total = 0; int [] current; int node; int h; int p; while (!queue.isEmpty()) { current = queue.remove(); node = current[0]; p = parents[node]; if (p > 0) { --counts[p]; if (p != 1 && (current[1] + 1) % maxL == 0 ) { ++total; } h = current[1] + 1; h %= maxL; maxDepth[p] = Math.max(maxDepth[p], h); if (counts[p] == 0 && p != 1) { queue.add(new int [] {p , maxDepth[p]}); } } } //System.out.println(maxL + " " + total); return total; } private static void dfs(int node, int height, int parent) { depth[node] = height; for (int child : graph[node]) { if (child == parent) continue; dfs(child, height + 1, node); } } private static class IOHandler { BufferedReader br; StringTokenizer st; public IOHandler() { 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()); } int [] readArray(int n) { int [] res = new int [n]; for (int i = 0; i < n; ++i) res[i] = nextInt(); return res; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
1e07629d950e4a337afdea881412cc78
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class D { public static void main(String[] args) throws IOException{ BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(bf.readLine()); while (t --> 0) { String[] line0=bf.readLine().split(" "); String[] line1=bf.readLine().split(" "); int n=Integer.parseInt(line0[0]); int k=Integer.parseInt(line0[1]); ArrayList<Integer>[] to=new ArrayList[n]; for (int i=0;i<n;i++) to[i]=new ArrayList<>(); for (int i=0;i<n-1;i++) { int v=Integer.parseInt(line1[i])-1; to[i+1].add(v); to[v].add(i+1); } int[] depth=new int[n]; int[] childDepth=new int[n]; for (int i=0;i<n;i++) { depth[i]=-1; childDepth[i]=-1; } dfs(n, to, depth, childDepth, 0, 0); //System.out.println("sy"); int lo=1,hi=n; while (lo < hi) { int mid=lo+(hi-lo)/2; boolean[] marked=new boolean[n]; guess(n, to, depth, childDepth, 0, mid, marked); int cnt=0; for (int i=0;i<n;i++) { if (depth[i] <= 1) continue; cnt += marked[i] ? 1 : 0; } //if (marked[0]) cnt--; if (cnt > k) lo=mid+1; else hi=mid; } //System.out.println("ans" + (lo)); System.out.println((lo)); } } static int dfs(int n, ArrayList<Integer>[] to, int[] depth, int[] childDepth, int curDepth, int i) { if (to[i].size()==0) return curDepth; depth[i]=curDepth; childDepth[i]=0; for (int child : to[i]) { if (depth[child] != -1) continue; childDepth[i]=Math.max(childDepth[i], dfs(n, to, depth, childDepth, curDepth+1, child)); } return childDepth[i]; } static int guess(int n, ArrayList<Integer>[] to, int[] depth, int[] childDepth, int i, int g, boolean[] marked) { int markCnt=1; for (int child : to[i]) { if (depth[child] < depth[i]) continue; markCnt=Math.max(markCnt, guess(markCnt, to, depth, childDepth, child, g, marked)+1); } if (markCnt >= g) { marked[i]=true; return 0; } return markCnt; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
25b59cc9b0ab21665eca98bfeb09cd42
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class q4 { static int count; public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n-1]; for(int i=0;i<n-1;i++){ arr[i] = sc.nextInt(); } System.out.println(solve(n,arr,k)); } } public static long solve(int n,int[] arr,int k){ ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); for(int i=0;i<=n;i++){ graph.add(new ArrayList<>()); } for(int i=0;i<arr.length;i++){ int parent = arr[i]; int child = i+2; graph.get(parent).add(child); graph.get(child).add(parent); } long lo = 1; long hi = n-1; while(hi-lo>1){ long mid = (lo+hi)/2; if(isSuff(graph,mid,k)==false){ lo = mid+1; } else{ hi = mid; } } if(isSuff(graph,lo,k)){ return lo; } else{ return hi; } } public static boolean isSuff(ArrayList<ArrayList<Integer>> graph,long mid,int k){ // boolean[] visited = new boolean[graph.size()+1]; count = 0; int z = dfs(graph,mid,1,-1); // System.out.println(mid+" "+count); return count <= k; } public static int dfs(ArrayList<ArrayList<Integer>> graph,long mid,int src,int parent){ int cp = 0; for(int i=0;i<graph.get(src).size();i++){ int dest = graph.get(src).get(i); if(dest == parent){ continue; } int z = dfs(graph,mid,dest,src); if(z == (int)mid && src != 1){ count++; z =0; } cp = Math.max(z,cp); } return cp+1; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
a4d927608c168ee8ce722b17a4e5790a
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; public class D { public static final int MOD998 = 998244353; public static final int MOD100 = 1000000007; static int count = 0; static int[][] graph; public static void main(String[] args) throws Exception { ContestScanner sc = new ContestScanner(); ContestPrinter cp = new ContestPrinter(); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int N = sc.nextInt(); int K = sc.nextInt(); EdgeData ed = new EdgeData(false, N); for (int n = 1; n < N; n++) { ed.addEdge(sc.nextInt() - 1, n); } graph = GraphBuilder.makeGraph(N, N - 1, ed.getFrom(), ed.getTo(), true); int ok = N; int ng = 0; while (ok - ng > 1) { count = 0; int x = (ok + ng) / 2; dfs(0, -1, x); if (count <= K) { ok = x; } else { ng = x; } } cp.println(ok); } cp.close(); } static public int dfs(int now, int prev, int border) { int max = 0; for (int v : graph[now]) { if (v == prev) { continue; } int d = dfs(v, now, border); if (now > 0) { if (d == border - 1) { count++; } else { max = Math.max(max, d + 1); } } } return max; } ////////////////// // My Library // ////////////////// public static int zeroOneBFS(int[][][] weighted_graph, int start, int goal) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); if (now == goal) { return dist[goal]; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return -1; } public static int[] zeroOneBFSAll(int[][][] weighted_graph, int start) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return dist; } public static long dijkstra(int[][][] weighted_graph, int start, int goal) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (now == goal) { return dist[goal]; } if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return -1; } public static long[] dijkstraAll(int[][][] weighted_graph, int start) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return dist; } public static class Pair<A, B> { public final A car; public final B cdr; public Pair(A car_, B cdr_) { car = car_; cdr = cdr_; } private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } private static int hc(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair<?, ?> rhs = (Pair<?, ?>) o; return eq(car, rhs.car) && eq(cdr, rhs.cdr); } @Override public int hashCode() { return hc(car) ^ hc(cdr); } } public static class Tuple1<A> extends Pair<A, Object> { public Tuple1(A a) { super(a, null); } } public static class Tuple2<A, B> extends Pair<A, Tuple1<B>> { public Tuple2(A a, B b) { super(a, new Tuple1<>(b)); } } public static class Tuple3<A, B, C> extends Pair<A, Tuple2<B, C>> { public Tuple3(A a, B b, C c) { super(a, new Tuple2<>(b, c)); } } public static class Tuple4<A, B, C, D> extends Pair<A, Tuple3<B, C, D>> { public Tuple4(A a, B b, C c, D d) { super(a, new Tuple3<>(b, c, d)); } } public static class Tuple5<A, B, C, D, E> extends Pair<A, Tuple4<B, C, D, E>> { public Tuple5(A a, B b, C c, D d, E e) { super(a, new Tuple4<>(b, c, d, e)); } } public static class PriorityQueueLogTime<T> { private PriorityQueue<T> queue; private Multiset<T> total; private int size = 0; public PriorityQueueLogTime() { queue = new PriorityQueue<>(); total = new Multiset<>(); } public PriorityQueueLogTime(Comparator<T> c) { queue = new PriorityQueue<>(c); total = new Multiset<>(); } public void clear() { queue.clear(); total.clear(); size = 0; } public boolean contains(T e) { return total.count(e) > 0; } public boolean isEmpty() { return size == 0; } public boolean offer(T e) { total.addOne(e); size++; return queue.offer(e); } public T peek() { if (total.isEmpty()) { return null; } simplify(); return queue.peek(); } public T poll() { if (total.isEmpty()) { return null; } simplify(); size--; T res = queue.poll(); total.removeOne(res); return res; } public void remove(T e) { total.removeOne(e); size--; } public int size() { return size; } private void simplify() { while (total.count(queue.peek()) == 0) { queue.poll(); } } } static int[][] scanGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 2); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraph(node, edge, arr[0], arr[1], undirected); } static int[][][] scanWeightedGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 3); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraphWithWeight(node, edge, arr[0], arr[1], arr[2], undirected); } static class EdgeData { private int capacity; private int[] from, to, weight; private int p = 0; private boolean weighted; public EdgeData(boolean weighted) { this(weighted, 500000); } public EdgeData(boolean weighted, int initial_capacity) { capacity = initial_capacity; from = new int[capacity]; to = new int[capacity]; weight = new int[capacity]; this.weighted = weighted; } public void addEdge(int u, int v) { if (weighted) { System.err.println("The graph is weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); from = newfrom; to = newto; capacity *= 2; } from[p] = u; to[p] = v; p++; } public void addEdge(int u, int v, int w) { if (!weighted) { System.err.println("The graph is NOT weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; int[] newweight = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); System.arraycopy(weight, 0, newweight, 0, capacity); from = newfrom; to = newto; weight = newweight; capacity *= 2; } from[p] = u; to[p] = v; weight[p] = w; p++; } public int[] getFrom() { int[] result = new int[p]; System.arraycopy(from, 0, result, 0, p); return result; } public int[] getTo() { int[] result = new int[p]; System.arraycopy(to, 0, result, 0, p); return result; } public int[] getWeight() { int[] result = new int[p]; System.arraycopy(weight, 0, result, 0, p); return result; } public int size() { return p; } } //////////////////////////////// // Atcoder Library for Java // //////////////////////////////// static class MathLib { private static long safe_mod(long x, long m) { x %= m; if (x < 0) x += m; return x; } private static long[] inv_gcd(long a, long b) { a = safe_mod(a, b); if (a == 0) return new long[] { b, 0 }; long s = b, t = a; long m0 = 0, m1 = 1; while (t > 0) { long u = s / t; s -= t * u; m0 -= m1 * u; long tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 < 0) m0 += b / s; return new long[] { s, m0 }; } public static long gcd(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return inv_gcd(a, b)[0]; } public static long lcm(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return a / gcd(a, b) * b; } public static long pow_mod(long x, long n, int m) { assert n >= 0; assert m >= 1; if (m == 1) return 0L; x = safe_mod(x, m); long ans = 1L; while (n > 0) { if ((n & 1) == 1) ans = (ans * x) % m; x = (x * x) % m; n >>>= 1; } return ans; } public static long[] crt(long[] r, long[] m) { assert (r.length == m.length); int n = r.length; long r0 = 0, m0 = 1; for (int i = 0; i < n; i++) { assert (1 <= m[i]); long r1 = safe_mod(r[i], m[i]), m1 = m[i]; if (m0 < m1) { long tmp = r0; r0 = r1; r1 = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 % m1 == 0) { if (r0 % m1 != r1) return new long[] { 0, 0 }; continue; } long[] ig = inv_gcd(m0, m1); long g = ig[0], im = ig[1]; long u1 = m1 / g; if ((r1 - r0) % g != 0) return new long[] { 0, 0 }; long x = (r1 - r0) / g % u1 * im % u1; r0 += x * m0; m0 *= u1; if (r0 < 0) r0 += m0; // System.err.printf("%d %d\n", r0, m0); } return new long[] { r0, m0 }; } public static long floor_sum(long n, long m, long a, long b) { long ans = 0; if (a >= m) { ans += (n - 1) * n * (a / m) / 2; a %= m; } if (b >= m) { ans += n * (b / m); b %= m; } long y_max = (a * n + b) / m; long x_max = y_max * m - b; if (y_max == 0) return ans; ans += (n - (x_max + a - 1) / a) * y_max; ans += floor_sum(y_max, a, m, (a - x_max % a) % a); return ans; } public static java.util.ArrayList<Long> divisors(long n) { java.util.ArrayList<Long> divisors = new ArrayList<>(); java.util.ArrayList<Long> large = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { divisors.add(i); if (i * i < n) large.add(n / i); } for (int p = large.size() - 1; p >= 0; p--) { divisors.add(large.get(p)); } return divisors; } } static class Multiset<T> extends java.util.TreeMap<T, Long> { public Multiset() { super(); } public Multiset(java.util.List<T> list) { super(); for (T e : list) this.addOne(e); } public long count(Object elm) { return getOrDefault(elm, 0L); } public void add(T elm, long amount) { if (!this.containsKey(elm)) put(elm, amount); else replace(elm, get(elm) + amount); if (this.count(elm) == 0) this.remove(elm); } public void addOne(T elm) { this.add(elm, 1); } public void removeOne(T elm) { this.add(elm, -1); } public void removeAll(T elm) { this.add(elm, -this.count(elm)); } public static <T> Multiset<T> merge(Multiset<T> a, Multiset<T> b) { Multiset<T> c = new Multiset<>(); for (T x : a.keySet()) c.add(x, a.count(x)); for (T y : b.keySet()) c.add(y, b.count(y)); return c; } } static class GraphBuilder { public static int[][] makeGraph(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][] graph = new int[NumberOfNodes][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = to[i]; if (undirected) graph[to[i]][--outdegree[to[i]]] = from[i]; } return graph; } public static int[][][] makeGraphWithWeight(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i] }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i] }; } return graph; } public static int[][][] makeGraphWithEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], i, 1 }; } return graph; } public static int[][][] makeGraphWithWeightAndEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i], i, 1 }; } return graph; } } static class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } } static class ModIntFactory { private final ModArithmetic ma; private final int mod; private final boolean usesMontgomery; private final ModArithmetic.ModArithmeticMontgomery maMontgomery; private ArrayList<Integer> factorial; private ArrayList<Integer> factorial_inversion; public ModIntFactory(int mod) { this.ma = ModArithmetic.of(mod); this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery; this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null; this.mod = mod; this.factorial = new ArrayList<>(); this.factorial_inversion = new ArrayList<>(); } public ModInt create(long value) { if ((value %= mod) < 0) value += mod; if (usesMontgomery) { return new ModInt(maMontgomery.generate(value)); } else { return new ModInt((int) value); } } private void prepareFactorial(int max) { factorial.ensureCapacity(max + 1); if (factorial.size() == 0) factorial.add(1); for (int i = factorial.size(); i <= max; i++) { factorial.add(ma.mul(factorial.get(i - 1), i)); } } public ModInt factorial(int i) { prepareFactorial(i); return create(factorial.get(i)); } public ModInt permutation(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create(ma.mul(factorial.get(n), factorial_inversion.get(n - r))); } return create(ma.div(factorial.get(n), factorial.get(n - r))); } public ModInt combination(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create( ma.mul(factorial.get(n), ma.mul(factorial_inversion.get(n - r), factorial_inversion.get(r)))); } return create(ma.div(factorial.get(n), ma.mul(factorial.get(r), factorial.get(n - r)))); } public void prepareFactorialInv(int max) { prepareFactorial(max); factorial_inversion.ensureCapacity(max + 1); for (int i = factorial_inversion.size(); i <= max; i++) { factorial_inversion.add(ma.inv(factorial.get(i))); } } public int getMod() { return mod; } public class ModInt { private int value; private ModInt(int value) { this.value = value; } public int mod() { return mod; } public int value() { if (ma instanceof ModArithmetic.ModArithmeticMontgomery) { return ((ModArithmetic.ModArithmeticMontgomery) ma).reduce(value); } return value; } public ModInt add(ModInt mi) { return new ModInt(ma.add(value, mi.value)); } public ModInt add(ModInt mi1, ModInt mi2) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt add(ModInt mi1, ModInt... mis) { ModInt mi = add(mi1); for (ModInt m : mis) mi.addAsg(m); return mi; } public ModInt add(long mi) { return new ModInt(ma.add(value, ma.remainder(mi))); } public ModInt sub(ModInt mi) { return new ModInt(ma.sub(value, mi.value)); } public ModInt sub(long mi) { return new ModInt(ma.sub(value, ma.remainder(mi))); } public ModInt mul(ModInt mi) { return new ModInt(ma.mul(value, mi.value)); } public ModInt mul(ModInt mi1, ModInt mi2) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mul(ModInt mi1, ModInt... mis) { ModInt mi = mul(mi1); for (ModInt m : mis) mi.mulAsg(m); return mi; } public ModInt mul(long mi) { return new ModInt(ma.mul(value, ma.remainder(mi))); } public ModInt div(ModInt mi) { return new ModInt(ma.div(value, mi.value)); } public ModInt div(long mi) { return new ModInt(ma.div(value, ma.remainder(mi))); } public ModInt inv() { return new ModInt(ma.inv(value)); } public ModInt pow(long b) { return new ModInt(ma.pow(value, b)); } public ModInt addAsg(ModInt mi) { this.value = ma.add(value, mi.value); return this; } public ModInt addAsg(ModInt mi1, ModInt mi2) { return addAsg(mi1).addAsg(mi2); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return addAsg(mi1).addAsg(mi2).addAsg(mi3); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt addAsg(ModInt... mis) { for (ModInt m : mis) addAsg(m); return this; } public ModInt addAsg(long mi) { this.value = ma.add(value, ma.remainder(mi)); return this; } public ModInt subAsg(ModInt mi) { this.value = ma.sub(value, mi.value); return this; } public ModInt subAsg(long mi) { this.value = ma.sub(value, ma.remainder(mi)); return this; } public ModInt mulAsg(ModInt mi) { this.value = ma.mul(value, mi.value); return this; } public ModInt mulAsg(ModInt mi1, ModInt mi2) { return mulAsg(mi1).mulAsg(mi2); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mulAsg(ModInt... mis) { for (ModInt m : mis) mulAsg(m); return this; } public ModInt mulAsg(long mi) { this.value = ma.mul(value, ma.remainder(mi)); return this; } public ModInt divAsg(ModInt mi) { this.value = ma.div(value, mi.value); return this; } public ModInt divAsg(long mi) { this.value = ma.div(value, ma.remainder(mi)); return this; } @Override public String toString() { return String.valueOf(value()); } @Override public boolean equals(Object o) { if (o instanceof ModInt) { ModInt mi = (ModInt) o; return mod() == mi.mod() && value() == mi.value(); } return false; } @Override public int hashCode() { return (1 * 37 + mod()) * 37 + value(); } } private static abstract class ModArithmetic { abstract int mod(); abstract int remainder(long value); abstract int add(int a, int b); abstract int sub(int a, int b); abstract int mul(int a, int b); int div(int a, int b) { return mul(a, inv(b)); } int inv(int a) { int b = mod(); if (b == 1) return 0; long u = 1, v = 0; while (b >= 1) { int t = a / b; a -= t * b; int tmp1 = a; a = b; b = tmp1; u -= t * v; long tmp2 = u; u = v; v = tmp2; } if (a != 1) { throw new ArithmeticException("divide by zero"); } return remainder(u); } int pow(int a, long b) { if (b < 0) throw new ArithmeticException("negative power"); int r = 1; int x = a; while (b > 0) { if ((b & 1) == 1) r = mul(r, x); x = mul(x, x); b >>= 1; } return r; } static ModArithmetic of(int mod) { if (mod <= 0) { throw new IllegalArgumentException(); } else if (mod == 1) { return new ModArithmetic1(); } else if (mod == 2) { return new ModArithmetic2(); } else if (mod == 998244353) { return new ModArithmetic998244353(); } else if (mod == 1000000007) { return new ModArithmetic1000000007(); } else if ((mod & 1) == 1) { return new ModArithmeticMontgomery(mod); } else { return new ModArithmeticBarrett(mod); } } private static final class ModArithmetic1 extends ModArithmetic { int mod() { return 1; } int remainder(long value) { return 0; } int add(int a, int b) { return 0; } int sub(int a, int b) { return 0; } int mul(int a, int b) { return 0; } int pow(int a, long b) { return 0; } } private static final class ModArithmetic2 extends ModArithmetic { int mod() { return 2; } int remainder(long value) { return (int) (value & 1); } int add(int a, int b) { return a ^ b; } int sub(int a, int b) { return a ^ b; } int mul(int a, int b) { return a & b; } } private static final class ModArithmetic998244353 extends ModArithmetic { private final int mod = 998244353; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmetic1000000007 extends ModArithmetic { private final int mod = 1000000007; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmeticMontgomery extends ModArithmeticDynamic { private final long negInv; private final long r2; private ModArithmeticMontgomery(int mod) { super(mod); long inv = 0; long s = 1, t = 0; for (int i = 0; i < 32; i++) { if ((t & 1) == 0) { t += mod; inv += s; } t >>= 1; s <<= 1; } long r = (1l << 32) % mod; this.negInv = inv; this.r2 = (r * r) % mod; } private int generate(long x) { return reduce(x * r2); } private int reduce(long x) { x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return generate((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } @Override int inv(int a) { return super.inv(reduce(a)); } @Override int pow(int a, long b) { return generate(super.pow(a, b)); } } private static final class ModArithmeticBarrett extends ModArithmeticDynamic { private static final long mask = 0xffff_ffffl; private final long mh; private final long ml; private ModArithmeticBarrett(int mod) { super(mod); /** * m = floor(2^64/mod) 2^64 = p*mod + q, 2^32 = a*mod + b => (a*mod + b)^2 = * p*mod + q => p = mod*a^2 + 2ab + floor(b^2/mod) */ long a = (1l << 32) / mod; long b = (1l << 32) % mod; long m = a * a * mod + 2 * a * b + (b * b) / mod; mh = m >>> 32; ml = m & mask; } private int reduce(long x) { long z = (x & mask) * ml; z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32); z = (x >>> 32) * mh + (z >>> 32); x -= z * mod; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } } private static class ModArithmeticDynamic extends ModArithmetic { final int mod; ModArithmeticDynamic(int mod) { this.mod = mod; } int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int sum = a + b; return sum >= mod ? sum - mod : sum; } int sub(int a, int b) { int sum = a - b; return sum < 0 ? sum + mod : sum; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } } } static class Convolution { /** * Find a primitive root. * * @param m A prime number. * @return Primitive root. */ private static int primitiveRoot(int m) { if (m == 2) return 1; if (m == 167772161) return 3; if (m == 469762049) return 3; if (m == 754974721) return 11; if (m == 998244353) return 3; int[] divs = new int[20]; divs[0] = 2; int cnt = 1; int x = (m - 1) / 2; while (x % 2 == 0) x /= 2; for (int i = 3; (long) (i) * i <= x; i += 2) { if (x % i == 0) { divs[cnt++] = i; while (x % i == 0) { x /= i; } } } if (x > 1) { divs[cnt++] = x; } for (int g = 2;; g++) { boolean ok = true; for (int i = 0; i < cnt; i++) { if (pow(g, (m - 1) / divs[i], m) == 1) { ok = false; break; } } if (ok) return g; } } /** * Power. * * @param x Parameter x. * @param n Parameter n. * @param m Mod. * @return n-th power of x mod m. */ private static long pow(long x, long n, int m) { if (m == 1) return 0; long r = 1; long y = x % m; while (n > 0) { if ((n & 1) != 0) r = (r * y) % m; y = (y * y) % m; n >>= 1; } return r; } /** * Ceil of power 2. * * @param n Value. * @return Ceil of power 2. */ private static int ceilPow2(int n) { int x = 0; while ((1L << x) < n) x++; return x; } /** * Garner's algorithm. * * @param c Mod convolution results. * @param mods Mods. * @return Result. */ private static long garner(long[] c, int[] mods) { int n = c.length + 1; long[] cnst = new long[n]; long[] coef = new long[n]; java.util.Arrays.fill(coef, 1); for (int i = 0; i < n - 1; i++) { int m1 = mods[i]; long v = (c[i] - cnst[i] + m1) % m1; v = v * pow(coef[i], m1 - 2, m1) % m1; for (int j = i + 1; j < n; j++) { long m2 = mods[j]; cnst[j] = (cnst[j] + coef[j] * v) % m2; coef[j] = (coef[j] * m1) % m2; } } return cnst[n - 1]; } /** * Pre-calculation for NTT. * * @param mod NTT Prime. * @param g Primitive root of mod. * @return Pre-calculation table. */ private static long[] sumE(int mod, int g) { long[] sum_e = new long[30]; long[] es = new long[30]; long[] ies = new long[30]; int cnt2 = Integer.numberOfTrailingZeros(mod - 1); long e = pow(g, (mod - 1) >> cnt2, mod); long ie = pow(e, mod - 2, mod); for (int i = cnt2; i >= 2; i--) { es[i - 2] = e; ies[i - 2] = ie; e = e * e % mod; ie = ie * ie % mod; } long now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_e[i] = es[i] * now % mod; now = now * ies[i] % mod; } return sum_e; } /** * Pre-calculation for inverse NTT. * * @param mod Mod. * @param g Primitive root of mod. * @return Pre-calculation table. */ private static long[] sumIE(int mod, int g) { long[] sum_ie = new long[30]; long[] es = new long[30]; long[] ies = new long[30]; int cnt2 = Integer.numberOfTrailingZeros(mod - 1); long e = pow(g, (mod - 1) >> cnt2, mod); long ie = pow(e, mod - 2, mod); for (int i = cnt2; i >= 2; i--) { es[i - 2] = e; ies[i - 2] = ie; e = e * e % mod; ie = ie * ie % mod; } long now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_ie[i] = ies[i] * now % mod; now = now * es[i] % mod; } return sum_ie; } /** * Inverse NTT. * * @param a Target array. * @param sumIE Pre-calculation table. * @param mod NTT Prime. */ private static void butterflyInv(long[] a, long[] sumIE, int mod) { int n = a.length; int h = ceilPow2(n); for (int ph = h; ph >= 1; ph--) { int w = 1 << (ph - 1), p = 1 << (h - ph); long inow = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { long l = a[i + offset]; long r = a[i + offset + p]; a[i + offset] = (l + r) % mod; a[i + offset + p] = (mod + l - r) * inow % mod; } int x = Integer.numberOfTrailingZeros(~s); inow = inow * sumIE[x] % mod; } } } /** * Inverse NTT. * * @param a Target array. * @param sumE Pre-calculation table. * @param mod NTT Prime. */ private static void butterfly(long[] a, long[] sumE, int mod) { int n = a.length; int h = ceilPow2(n); for (int ph = 1; ph <= h; ph++) { int w = 1 << (ph - 1), p = 1 << (h - ph); long now = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { long l = a[i + offset]; long r = a[i + offset + p] * now % mod; a[i + offset] = (l + r) % mod; a[i + offset + p] = (l - r + mod) % mod; } int x = Integer.numberOfTrailingZeros(~s); now = now * sumE[x] % mod; } } } /** * Convolution. * * @param a Target array 1. * @param b Target array 2. * @param mod NTT Prime. * @return Answer. */ public static long[] convolution(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; if (n == 0 || m == 0) return new long[0]; int z = 1 << ceilPow2(n + m - 1); { long[] na = new long[z]; long[] nb = new long[z]; System.arraycopy(a, 0, na, 0, n); System.arraycopy(b, 0, nb, 0, m); a = na; b = nb; } int g = primitiveRoot(mod); long[] sume = sumE(mod, g); long[] sumie = sumIE(mod, g); butterfly(a, sume, mod); butterfly(b, sume, mod); for (int i = 0; i < z; i++) { a[i] = a[i] * b[i] % mod; } butterflyInv(a, sumie, mod); a = java.util.Arrays.copyOf(a, n + m - 1); long iz = pow(z, mod - 2, mod); for (int i = 0; i < n + m - 1; i++) a[i] = a[i] * iz % mod; return a; } /** * Convolution. * * @param a Target array 1. * @param b Target array 2. * @param mod Any mod. * @return Answer. */ public static long[] convolutionLL(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; if (n == 0 || m == 0) return new long[0]; int mod1 = 754974721; int mod2 = 167772161; int mod3 = 469762049; long[] c1 = convolution(a, b, mod1); long[] c2 = convolution(a, b, mod2); long[] c3 = convolution(a, b, mod3); int retSize = c1.length; long[] ret = new long[retSize]; int[] mods = { mod1, mod2, mod3, mod }; for (int i = 0; i < retSize; ++i) { ret[i] = garner(new long[] { c1[i], c2[i], c3[i] }, mods); } return ret; } /** * Convolution by ModInt. * * @param a Target array 1. * @param b Target array 2. * @return Answer. */ public static java.util.List<ModIntFactory.ModInt> convolution(java.util.List<ModIntFactory.ModInt> a, java.util.List<ModIntFactory.ModInt> b) { int mod = a.get(0).mod(); long[] va = a.stream().mapToLong(ModIntFactory.ModInt::value).toArray(); long[] vb = b.stream().mapToLong(ModIntFactory.ModInt::value).toArray(); long[] c = convolutionLL(va, vb, mod); ModIntFactory factory = new ModIntFactory(mod); return java.util.Arrays.stream(c).mapToObj(factory::create).collect(java.util.stream.Collectors.toList()); } /** * Naive convolution. (Complexity is O(N^2)!!) * * @param a Target array 1. * @param b Target array 2. * @param mod Mod. * @return Answer. */ public static long[] convolutionNaive(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; int k = n + m - 1; long[] ret = new long[k]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i + j] += a[i] * b[j] % mod; ret[i + j] %= mod; } } return ret; } } static class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in) { this.in = in; } public ContestScanner() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } 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(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[][] nextIntArrayMulti(int length, int width) { int[][] arrays = new int[width][length]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) arrays[j][i] = this.nextInt(); } return arrays; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } static class ContestPrinter extends java.io.PrintWriter { public ContestPrinter(java.io.PrintStream stream) { super(stream); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } } public static void safeSort(int[] array) { Integer[] temp = new Integer[array.length]; for (int n = 0; n < array.length; n++) { temp[n] = array[n]; } Arrays.sort(temp); for (int n = 0; n < array.length; n++) { array[n] = temp[n]; } } public static void safeSort(long[] array) { Long[] temp = new Long[array.length]; for (int n = 0; n < array.length; n++) { temp[n] = array[n]; } Arrays.sort(temp); for (int n = 0; n < array.length; n++) { array[n] = temp[n]; } } public static void safeSort(double[] array) { Double[] temp = new Double[array.length]; for (int n = 0; n < array.length; n++) { temp[n] = array[n]; } Arrays.sort(temp); for (int n = 0; n < array.length; n++) { array[n] = temp[n]; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
c42b0988e2fc7a810335124e8231a379
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
// package c1739; // // Educational Codeforces Round 136 (Rated for Div. 2) 2022-09-29 07:35 // D. Reset K Edges // https://codeforces.com/contest/1739/problem/D // time limit per test 4 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given a rooted tree, consisting of n vertices. The vertices are numbered from 1 to n, the // root is the vertex 1. // // You can perform the following operation k times: // * choose an edge (v, u) of the tree such that v is a parent of u; // * remove the edge (v, u); // * add an edge (1, u) (i.?e. make u with its subtree a child of the root). // // of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges // on the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, // and the depth of all its children is 1. // // What's the smallest height of the tree that can be achieved? // // Input // // The first line contains a single integer t (1 <= t <= 10^4)-- the number of testcases. // // The first line of each testcase contains two integers n and k (2 <= n <= 2 * 10^5; 0 <= k <= n - // 1)-- the number of vertices in the tree and the maximum number of operations you can perform. // // The second line contains n-1 integers p_2, p_3, ..., p_n (1 <= p_i < i)-- the parent of the i-th // vertex. Vertex 1 is the root. // // The sum of n over all testcases doesn't exceed 2 * 10^5. // // Output // // For each testcase, print a single integer-- the smallest height of the tree that can achieved by // performing k operations. // // Example /* input: 5 5 1 1 1 2 2 5 2 1 1 2 2 6 0 1 2 3 4 5 6 1 1 2 3 4 5 4 3 1 1 1 output: 2 1 5 3 1 */ // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Random; import java.util.StringTokenizer; public class C1739D { static final int MOD = 998244353; static final Random RAND = new Random(); static int solve(int[] p, int k) { int n = p.length; List<Integer>[] children = new ArrayList[n]; for (int i = 0; i < n; i++) { children[i] = new ArrayList<>(); } for (int i = 1; i < n; i++) { children[p[i]].add(i); } // [subtree-depth] (leaf node depth is 1) int[] depths = new int[n]; { Queue<Integer> q = new LinkedList<>(); int[] degs = new int[n]; for (int i = 0; i < n; i++) { degs[i] = children[i].size(); if (degs[i] == 0) { q.add(i); depths[i] = 1; } } while (!q.isEmpty()) { int v = q.poll(); if (!children[v].isEmpty()) { for (int w : children[v]) { depths[v] = Math.max(depths[v], 1 + depths[w]); } } if (p[v] >= 0) { degs[p[v]]--; if (degs[p[v]] == 0) { q.add(p[v]); } } } } // System.out.format("%s\n", Arrays.deepToString(depths)); if (k == 0) { return depths[0] - 1; } // binary search the smallest height can be achieved with <= k cuts { int low = 1; int hig = depths[0]; int ans = hig; while (low <= hig) { int mid = (low + hig) / 2; Queue<Integer> q = new LinkedList<>(); int[] degs = new int[n]; for (int i = 0; i < n; i++) { degs[i] = children[i].size(); if (degs[i] == 0) { q.add(i); } } int cuts = 0; int[] dep = new int[n]; System.arraycopy(depths, 0, dep, 0, n); while (!q.isEmpty()) { int v = q.poll(); // count number of children to cut int maxc = 0; for (int w : children[v]) { // If we cut the child and attach directly to the root, what's the height int h = dep[w]; // System.out.format(" v:%d w:%d h:%d\n", v, w, h); if (h >= mid) { cuts++; } else { maxc = Math.max(maxc, dep[w]); } } dep[v] = 1 + maxc; if (p[v] >= 0) { degs[p[v]]--; if (degs[p[v]] == 0 && p[v] != 0) { q.add(p[v]); } } } // System.out.format(" low:%d hig:%d mid:%d cuts:%d\n", low, hig, mid, cuts); if (cuts <= k) { ans = Math.min(ans, mid); hig = mid - 1; } else { low = mid + 1; } } return ans; } } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int k = in.nextInt(); int[] p = new int[n]; for (int i = 1; i < n; i++) { p[i] = in.nextInt() - 1; } int ans = solve(p, k); System.out.println(ans); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
eb25bd3fdf1f0672d02006335d9a4dc6
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
// package c1739; // // Educational Codeforces Round 136 (Rated for Div. 2) 2022-09-29 07:35 // D. Reset K Edges // https://codeforces.com/contest/1739/problem/D // time limit per test 4 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given a rooted tree, consisting of n vertices. The vertices are numbered from 1 to n, the // root is the vertex 1. // // You can perform the following operation k times: // * choose an edge (v, u) of the tree such that v is a parent of u; // * remove the edge (v, u); // * add an edge (1, u) (i.?e. make u with its subtree a child of the root). // // of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges // on the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, // and the depth of all its children is 1. // // What's the smallest height of the tree that can be achieved? // // Input // // The first line contains a single integer t (1 <= t <= 10^4)-- the number of testcases. // // The first line of each testcase contains two integers n and k (2 <= n <= 2 * 10^5; 0 <= k <= n - // 1)-- the number of vertices in the tree and the maximum number of operations you can perform. // // The second line contains n-1 integers p_2, p_3, ..., p_n (1 <= p_i < i)-- the parent of the i-th // vertex. Vertex 1 is the root. // // The sum of n over all testcases doesn't exceed 2 * 10^5. // // Output // // For each testcase, print a single integer-- the smallest height of the tree that can achieved by // performing k operations. // // Example /* input: 5 5 1 1 1 2 2 5 2 1 1 2 2 6 0 1 2 3 4 5 6 1 1 2 3 4 5 4 3 1 1 1 output: 2 1 5 3 1 */ // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Random; import java.util.StringTokenizer; public class C1739D { static final int MOD = 998244353; static final Random RAND = new Random(); static int solve(int[] p, int k) { int n = p.length; List<Integer>[] children = new ArrayList[n]; for (int i = 0; i < n; i++) { children[i] = new ArrayList<>(); } for (int i = 1; i < n; i++) { children[p[i]].add(i); } // [distance_to_root, subtree-depth] (leaf node depth is 1) int[][] depths = new int[n][2]; { Queue<Integer> q = new LinkedList<>(); q.add(0); while (!q.isEmpty()) { int v = q.poll(); for (int w : children[v]) { depths[w][0] = depths[v][0] + 1; q.add(w); } } } { Queue<Integer> q = new LinkedList<>(); int[] degs = new int[n]; for (int i = 0; i < n; i++) { degs[i] = children[i].size(); if (degs[i] == 0) { q.add(i); depths[i][1] = 1; } } while (!q.isEmpty()) { int v = q.poll(); if (!children[v].isEmpty()) { for (int w : children[v]) { depths[v][1] = Math.max(depths[v][1], 1 + depths[w][1]); } } if (p[v] >= 0) { degs[p[v]]--; if (degs[p[v]] == 0) { q.add(p[v]); } } } } // System.out.format("%s\n", Arrays.deepToString(depths)); if (k == 0) { return depths[0][1] - 1; } // binary search the smallest height can be achieved with <= k cuts { int low = 1; int hig = depths[0][1]; int ans = hig; while (low <= hig) { int mid = (low + hig) / 2; Queue<Integer> q = new LinkedList<>(); int[] degs = new int[n]; for (int i = 0; i < n; i++) { degs[i] = children[i].size(); if (degs[i] == 0) { q.add(i); } } int cuts = 0; int[][] dep = new int[n][2]; for (int i = 0; i < n; i++) { dep[i][0] = depths[i][0]; dep[i][1] = depths[i][1]; } while (!q.isEmpty()) { int v = q.poll(); // count number of children to cut int maxc = 0; for (int w : children[v]) { // If we cut the child and attach directly to the root, what's the height int h = dep[w][1]; // System.out.format(" v:%d w:%d h:%d\n", v, w, h); if (h >= mid) { cuts++; } else { maxc = Math.max(maxc, dep[w][1]); } } dep[v][1] = 1 + maxc; if (p[v] >= 0) { degs[p[v]]--; if (degs[p[v]] == 0 && p[v] != 0) { q.add(p[v]); } } } // System.out.format(" low:%d hig:%d mid:%d cuts:%d\n", low, hig, mid, cuts); if (cuts <= k) { ans = Math.min(ans, mid); hig = mid - 1; } else { low = mid + 1; } } return ans; } } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int k = in.nextInt(); int[] p = new int[n]; for (int i = 1; i < n; i++) { p[i] = in.nextInt() - 1; } int ans = solve(p, k); System.out.println(ans); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
ab2b27f30616dade9ae54526f5c77ffb
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class d { static int maxN = 200005; public static int[] p = new int[maxN]; static ArrayList<Integer>[] c = new ArrayList[maxN]; static TreeMap<Integer, Integer>[] cdepth = new TreeMap[maxN]; static int n; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int nc = Integer.parseInt(in.readLine()); StringBuilder b = new StringBuilder(); for(int i = 0; i < maxN; i++){ c[i] = new ArrayList<>(); cdepth[i] = new TreeMap<>(); } for (int cn = 0; cn < nc; cn++) { StringTokenizer tokenizer = new StringTokenizer(in.readLine()); n = Integer.parseInt(tokenizer.nextToken()); int k = Integer.parseInt(tokenizer.nextToken()); for (int i = 0; i < n; i++) { c[i].clear(); } Arrays.fill(p, -1); tokenizer = new StringTokenizer(in.readLine()); for (int i = 1; i < n; i++) { p[i] = Integer.parseInt(tokenizer.nextToken()) - 1; c[p[i]].add(i); } int low = 1; int high = 200005; while (low < high) { int mid = low + (high - low) / 2; for (int i = 0; i < n; i++) { cdepth[i].clear(); } int kcnt = dfscnt(0, mid); if (kcnt <= k) { high = mid; } else { low = mid + 1; } } b.append(low + "\n"); } System.out.print(b); in.close(); } static int dfscnt(int cur, int k) { if (k == 1) { return n - 1 - c[0].size(); } int ans = 0; for (int i : c[cur]) { ans += dfscnt(i, k); } // up[cur]>k if (cur != 0 && p[cur] != 0) { if (cdepth[cur].size() > 0 && cdepth[cur].lastKey() >= k - 2) ans++; else { int down = cdepth[cur].size() > 0 ? cdepth[cur].lastKey() + 1 : 0; if (!cdepth[p[cur]].containsKey(down)) { cdepth[p[cur]].put(down, 0); } cdepth[p[cur]].put(down, cdepth[p[cur]].get(down) + 1); } } return ans; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
a5a92e1cdfc4bbd2dc045a9b28f668da
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class Shivaya { static boolean prime[]; static class Pair implements Comparable<Pair> {int a;int b;Pair(int a, int b) {this.a = a;this.b = b;}public boolean equals(Object o) {if (o instanceof Pair) {Pair p = (Pair) o;return p.a == a && p.b == b;}return false;}public int hashCode() {int hash = 5;hash = 17 * hash + this.a;return hash;}public int compareTo(Pair o){if(this.a!=o.a)return this.a-o.a;else return this.b-o.b;}} static long power(long x, long y, long p) {if (y == 0) return 1;if (x == 0) return 0;long res = 1l;x = x % p;while (y > 0) {if (y % 2 == 1) res = (res * x) % p;y = y >> 1;x = (x * x) % p;}return res;} static void sort(long[] a) {ArrayList<Long> l = new ArrayList<>();for (long i : a) l.add(i);Collections.sort(l);for (int i = 0; i < a.length; i++) a[i] = l.get(i);} static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in));StringTokenizer st = new StringTokenizer("");String next() {while (!st.hasMoreTokens()) try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}return st.nextToken();}int nextInt() {return Integer.parseInt(next());}double nextDouble() {return Double.parseDouble(next());}int[] readArray(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = nextInt();return a;}long[] readlongArray(int n) {long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nextLong();return a;}long nextLong() {return Long.parseLong(next());}} static void sieveOfEratosthenes(int n) {prime = new boolean[n + 1];for (int i = 0; i <= n; i++) prime[i] = true;for (int p = 2; p * p <= n; p++) {if (prime[p] == true) {for (int i = p * p; i <= n; i += p) prime[i] = false;}}} public static int log2(int x) { return (int) (Math.log(x) / Math.log(2)); } static long binomialCoeff(long n, long r) {if (r > n) return 0l;long m = 998244353l;long inv[] = new long[(int) r + 1];inv[0] = 1;if (r + 1 >= 2)inv[1] = 1;for (int i = 2; i <= r; i++) {inv[i] = m - (m / i) * inv[(int) (m % i)] % m;}long ans = 1l;for (int i = 2; i <= r; i++) {ans = (int) (((ans % m) * (inv[i] % m)) % m);}for (int i = (int) n; i >= (n - r + 1); i--) {ans = (int) (((ans % m) * (i % m)) % m);}return ans;} public static long gcd(long a, long b) {if (b == 0) {return a;}return gcd(b, a % b);} static BigInteger bi(String str) { return new BigInteger(str); } static FastScanner fs = null; static long mod = 1_000_000_007; static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}, }; static int k; static long dp[][]; static ArrayList<Integer> al[]; static long m = 998244353l; static int n; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); outer: while (t-- > 0) { n = fs.nextInt(); k = fs.nextInt(); al = new ArrayList[n]; int p[] = fs.readArray(n-1); for(int i =0;i<n;i++){ al[i] = new ArrayList<>(); } for(int i=0;i<n-1;i++){ al[p[i]-1].add(i+1); } int l=1; int r = n; int ans=n; while(l<=r){ int mid = (l+r)/2; if(check(mid)){ ans = mid; r = mid-1; }else{ l = mid+1; } } out.println(ans); } out.close(); } static int level[]; static int count=0; public static boolean check(int mid){ level = new int[n]; count=0; dfs(0,mid); return count<=k; } public static void dfs(int child,int mh){ int maxn=0; for(int v:al[child]){ dfs(v,mh); if(level[v]!=mh) maxn = Math.max(maxn,level[v]); if(level[v]==mh && child!=0) count++; } if(maxn==mh){ level[child]=1; }else{ level[child] = maxn+1; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
45292b03d7edfadc4ae4160262952c97
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),k=Integer.parseInt(s[1]); ArrayList<Integer> g[]=new ArrayList[n]; int i; for(i=0;i<n;i++) g[i]=new ArrayList<>(); s=bu.readLine().split(" "); for(i=1;i<n;i++) { int p=Integer.parseInt(s[i-1])-1; g[p].add(i); } int l=1,r=n,mid,ans=r,d[]=new int[n]; while(l<=r) { mid=(l+r)>>1; int moves=dfs(g,0,-1,d,mid); if(moves<=k) { ans=mid; r=mid-1; } else l=mid+1; } sb.append(ans+"\n"); } System.out.print(sb); } static int dfs(ArrayList<Integer> g[],int n,int p,int d[],int max) { int del=0; d[n]=0; for(int x:g[n]) if(x!=p) { del+=dfs(g,x,n,d,max); d[n]=Math.max(d[n],d[x]+1); } if(p!=0 && n!=0 && d[n]==max-1) {del++; d[n]=-1;} return del; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
91d5c81e1bb38948e61a04db393be8b9
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; public class Main { public static int count=0; public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); for(int w=1;w<=t;w++) { int n = scn.nextInt(); int k = scn.nextInt(); ArrayList<Integer> [] graph = new ArrayList[n+1]; for(int a=0;a<=n;a++) { graph[a]=new ArrayList<Integer>(); } for(int a=2;a<=n;a++) { int p = scn.nextInt(); graph[p].add(a); } int lo = 0; int hi = n; while(hi-lo>1) { int mid = (lo+hi)/2; count=0; dfs(1,-1,mid,graph); //System.out.println(mid+" "+count); if(count<=k) { hi = mid; } else { lo = mid; } } System.out.println(hi); } } public static int dfs(int now, int prev, int poss,ArrayList<Integer> [] graph) { //System.out.println(prev+" * "+now+" "+poss); int max = 0; for (int v : graph[now]) { if (v == prev) { continue; } int d = dfs(v, now, poss,graph); if (now > 1) { if (d == poss - 1) { count++; } else { max = Math.max(max, d + 1); } } } return max; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
ed756fdc733ee826f8ef26ff3197d188
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class ResetKEdges { static ArrayList<ArrayList<Integer>> al = new ArrayList<>(); static int n = 0; static int k = 0; static int count = 0; 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) { String[] st = br.readLine().split(" "); n = Integer.parseInt(st[0]); k = Integer.parseInt(st[1]); String[] str = br.readLine().split(" "); for(int i = 0; i < n; i++) { al.add(new ArrayList<>()); } for(int i = 0; i < n-1; i++) { al.get(Integer.parseInt(str[i]) - 1).add(i+1); } int l = 0; int r = n; while(r > l+1) { int mid = (l+r)/2; if(check(mid)) r = mid; else l = mid; } System.out.println(r); al.clear(); } } static boolean check(int mid) { count = 0; dfs(0, -1, mid); return count <= k; } static int dfs(int x, int par, int mid) { int height = 1; for(int ch: al.get(x)) { height = Math.max(dfs(ch, x, mid) + 1, height); } if(height == mid && par != 0 && x != 0) { count++; return 0; } return height; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
77215bb65ca58aec9997056e2200d398
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { long mod1 = (long) 1e9 + 7; int mod2 = 998244353; ArrayList<ArrayList<Integer>> list; int n, k; int need=0; int mid=0; int height[]; public void solve() throws Exception { int t = sc.nextInt(); while (t-- > 0) { n=sc.nextInt(); k=sc.nextInt(); height = new int[n]; list = new ArrayList<ArrayList<Integer>>(); for(int i=0;i<n;i++) { list.add(new ArrayList<Integer>()); } for(int i=1;i<n;i++) { int u=sc.nextInt(); u--; list.get(i).add(u); list.get(u).add(i); } if(n==1) { out.println(0); continue; } int lo = 1, hi = n-1; int ans=n; while(lo <= hi) { mid = (lo+hi)/2; need=0; height = new int[n]; dfs(0, -1); // out.println(mid+" "+need); if(need <= k) { ans = Math.min(ans, mid); hi = mid-1; } else { lo = mid+1; } } out.println(ans); } } public void dfs(int u, int v) { height[u] = 0; for(int i:list.get(u)) { if(i==v) continue; dfs(i, u); height[u] = Math.max(height[u], height[i]+1); } if(u==0) return; if(height[u] == mid-1) { if(v!=0) { need++; height[u] = -1; } } } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static long ncr(int n, int r, long p) { if (r > n) return 0l; if (r > n - r) r = n - r; long C[] = new long[r + 1]; C[0] = 1; for (int i = 1; i <= n; i++) { for (int j = Math.min(i, r); j > 0; j--) C[j] = (C[j] + C[j - 1]) % p; } return C[r] % p; } void sieveOfEratosthenes(boolean prime[], int size) { for (int i = 0; i < size; i++) prime[i] = true; for (int p = 2; p * p < size; p++) { if (prime[p] == true) { for (int i = p * p; i < size; i += p) prime[i] = false; } } } static int LowerBound(int a[], int x) { // smallest index having value >= 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; } static int UpperBound(int a[], int x) {// biggest index having value <= 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 long power(long x, long y, long p) { long res = 1; // out.println(x+" "+y); x = x % p; if (x == 0) return 0; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable uncaught) { Solution.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); if (Solution.uncaught != null) { throw Solution.uncaught; } } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public int[] readArray(int n) throws Exception { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
ccf0a361747cf9ca7a3ba78a082d8431
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import java.util.*; import java.lang.*; import java.io.*; public class SolutionD { static int MAX = 200005; static List<Integer>[] graph = new List[MAX]; static int[] dp = new int[MAX]; // max depth in subtree of node i. static int operations; public static void main(String[] args) throws Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = sc.nextInt(); for (int t = 1; t <= test; t++) { solve(t); } out.close(); } private static void solve(int t) { int n = sc.nextInt(); int k = sc.nextInt(); for (int i = 1; i <= n; i++) { graph[i] = new ArrayList<>(); } for (int i = 2; i <= n; i++) { int parent = sc.nextInt(); graph[parent].add(i); } int minHeight = binarySearch(n, k); out.println(minHeight - 1); } private static int binarySearch(int n, int k) { int minHeight = n, low = 2, high = n; while (low <= high) { int mid = low + (high - low) / 2; operations = 0; if (canResetEdges(n, k, mid)) { minHeight = mid; high = mid - 1; }else { low = mid + 1; } } return minHeight; } private static boolean canResetEdges(int n, int k, int maxHeight) { for (int i = 0; i <= n; i++) { dp[i] = 0; } dfs(1, maxHeight); return operations <= k; } private static void dfs(int currNode, int maxHeight) { for (int adjacentNode : graph[currNode]) { dfs(adjacentNode, maxHeight); if (dp[adjacentNode] + 1 == maxHeight && currNode != 1) { // reset edge operations++; }else { dp[currNode] = Math.max(dp[currNode], dp[adjacentNode]); } } dp[currNode]++; } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
7d9657374aa01786f3db9d41f7ccbb17
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.HashSet; import java.util.StringTokenizer; public class D { private final static String inputFileName = null; private final static String outputFileName = null; public static void main(String[] args) { try (Solver solver = new Solver(inputFileName, outputFileName)) { solver.solve(); } } private static class Solver implements AutoCloseable { int checkCost(HashSet<Integer>[] graph, int[] depth, int node, int targetDepth) { int res = 0; depth[node] = 1; for (int next : graph[node]) { res += checkCost(graph, depth, next, targetDepth); depth[node] = Math.max(depth[node], depth[next] + 1); } if (node != 0 && !graph[0].contains(node) && depth[node] >= targetDepth) { depth[node] = 0; res++; } return res; } public void solve() { int t = reader.readInt(); while (t-- > 0) { int n = reader.readInt(); int k = reader.readInt(); HashSet<Integer>[] graph = new HashSet[n]; for (int i = 0; i < n; i++) graph[i] = new HashSet<>(); for (int i = 1; i < n; i++) { int parent = reader.readInt() - 1; graph[parent].add(i); } int[] depth = new int[n]; checkCost(graph, depth, 0, n); int st = 1, en = n-1; while (st < en) { int mid = (st + en) / 2; int cost = checkCost(graph, depth, 0, mid); if (cost <= k) en = mid; else st = mid + 1; } writer.writeLine(en); } } private final FastReader reader; private final FastWriter writer; private Solver(String inputFileName, String outputFileName) { this.reader = inputFileName == null ? new FastReader() : new FastReader(inputFileName); this.writer = outputFileName == null ? new FastWriter() : new FastWriter(outputFileName); } @Override public void close() { reader.close(); writer.close(); } } private static class FastReader implements Closeable { private final BufferedReader bufferedReader; private StringTokenizer stringTokenizer; public FastReader() { bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String fileName) { try { bufferedReader = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public String readLine() { try { return bufferedReader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public String read() { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) stringTokenizer = new StringTokenizer(readLine()); return stringTokenizer.nextToken(); } public int readInt() { return Integer.parseInt(read()); } public long readLong() { return Long.parseLong(read()); } public double readDouble() { return Double.parseDouble(read()); } @Override public void close() { try { bufferedReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } } private static class FastWriter implements Closeable { private final BufferedWriter bufferedWriter; public FastWriter() { bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out)); } public FastWriter(String fileName) { try { bufferedWriter = new BufferedWriter(new FileWriter(fileName)); } catch (IOException e) { throw new RuntimeException(e); } } public void newLine() { try { bufferedWriter.newLine(); } catch (IOException e) { throw new RuntimeException(e); } } public void write(Object object) { try { bufferedWriter.write(object.toString()); } catch (IOException e) { throw new RuntimeException(e); } } public void writeLine(Object object) { write(object); newLine(); } public void flush() { try { bufferedWriter.flush(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void close() { try { bufferedWriter.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
bb55e3196f6bf60ed7df6442287841ad
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class Main { static Scanner sc; static PrintWriter out; public static void main(String[] args) { sc = new Scanner(System.in); out = new PrintWriter(System.out); int t = 1; if (true) { t = sc.nextInt(); } for(int i=0; i<t; i++) { new Main().solve(); } out.flush(); } public void solve() { int n = sc.nextInt(); T t = new T(n); int k = sc.nextInt(); for(int i=1; i<n; i++) { int p = sc.nextInt()-1; t.addEdge(p, i); } t.calcDepth(0); int l=0; int r=n; while(r-l>1) { int mid = (r+l)/2; if(t.test(mid)<=k) { r = mid; } else { l = mid; } } out.println(r); } static class T { int n; List<Integer>[] next; int[] d; //int[] bd; int[] bdc; int[] p; TreeMap<Integer, Integer>[] maps; T(int n) { this.n = n; next = new ArrayList[n]; //maps = new TreeMap[n]; p = new int[n]; //bd = new int[n]; p[0] = -1; for(int i=0; i<n; i++) { next[i] = new ArrayList<Integer>(); } calcDepth(0); } public void calcDepth(int root) { d = new int[n]; calcDepth(root, -1, 0); } void calcDepth(int v, int parent, int depth) { d[v] = depth; /* bd[v] = 0; maps[v] = new TreeMap<>(); maps[v].put(0, 0); */ for(int c : next[v]) { calcDepth(c, v, depth+1); } /* if(parent != -1) { int rd = maps[v].lastKey()+1; maps[parent].put(rd, maps[parent].getOrDefault(rd, 0) + 1); bd[parent] = Math.max(bd[parent], rd); } */ } void addEdge(int a, int b) { next[a].add(b); p[b] = a; } void dfs(int u, int parent) { for(int v : next[u]) { if(v != parent) dfs(v, u); } } int test(int len) { bdc = new int[n]; int res = 0; for(int i=n-1; i>0; i--) { for(int sub : next[i]) { bdc[i] = Math.max(bdc[i], bdc[sub]+1); } if(d[i] >= 2 && bdc[i] == len-1) { bdc[i] = -1; res++; } } return res; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
f6ae7f5b912749a73a79e29be7ca9cd6
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; public class Main { private static final void solve() throws IOException { final int n = ni(), k = ni(), m = n - 1; var p = new int[m]; for (int i = 0; i < m; i++) p[i] = ni() - 1; var ty_cnt = new int[n]; for (int i = 0; i < m; i++) { ty_cnt[i + 1]++; ty_cnt[p[i]]++; } g = new int[n][]; for (int i = 0; i < n; i++) g[i] = new int[ty_cnt[i]]; Arrays.fill(ty_cnt, 0); for (int i = 0; i < m; i++) { g[i + 1][ty_cnt[i + 1]++] = p[i]; g[p[i]][ty_cnt[p[i]]++] = i + 1; } d = new int[n]; int ok = n, ng = 0; while (ok - ng != 1) { final int vs = ok + ng + 1 >> 1; cnt = 0; lim = vs; f(0, -1); if (cnt <= k) ok = vs; else ng = vs; } ou.println(ok); return; } private static int cnt = -1, lim = -1; private static int[] d; private static int[][] g; private static final void f(int to, int no) { d[to] = 0; for (int i : g[to]) { if (i == no) continue; f(i, to); final int ch = d[i] + 1; if (ch == lim) { if (to != 0) cnt++; } else d[to] = Math.max(d[to], ch); } } public static void main(String[] args) throws IOException { for (int i = 0, t = ni(); i < t; i++) solve(); ou.flush(); } private static final int ni() throws IOException { return sc.nextInt(); } private static final int[] ni(int n) throws IOException { return sc.nextIntArray(n); } private static final long nl() throws IOException { return sc.nextLong(); } private static final long[] nl(int n) throws IOException { return sc.nextLongArray(n); } private static final String ns() throws IOException { return sc.next(); } private static final ContestInputStream sc = new ContestInputStream(); private static final ContestOutputStream ou = new ContestOutputStream(); } final class ContestInputStream extends FilterInputStream { protected final byte[] buf; protected int pos = 0; protected int lim = 0; private final char[] cbuf; public ContestInputStream() { super(System.in); this.buf = new byte[1 << 13]; this.cbuf = new char[1 << 20]; } boolean hasRemaining() throws IOException { if (pos < lim) return true; lim = in.read(buf); pos = 0; return lim > 0; } final int remaining() throws IOException { if (pos >= lim) { lim = in.read(buf); pos = 0; } return lim - pos; } @Override public final int available() throws IOException { if (pos < lim) return lim - pos + in.available(); return in.available(); } @Override public final long skip(long n) throws IOException { if (pos < lim) { int rem = lim - pos; if (n < rem) { pos += n; return n; } pos = lim; return rem; } return in.skip(n); } @Override public final int read() throws IOException { if (hasRemaining()) return buf[pos++]; return -1; } @Override public final int read(byte[] b, int off, int len) throws IOException { if (pos < lim) { int rem = Math.min(lim - pos, len); for (int i = 0; i < rem; i++) b[off + i] = buf[pos + i]; pos += rem; return rem; } return in.read(b, off, len); } public final char[] readToken() throws IOException { int cpos = 0; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } char[] arr = new char[cpos]; for (int i = 0; i < cpos; i++) arr[i] = cbuf[i]; return arr; } public final int readToken(char[] cbuf, int off) throws IOException { int cpos = off; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return cpos - off; } public final int readToken(char[] cbuf) throws IOException { return readToken(cbuf, 0); } public final String next() throws IOException { int cpos = 0; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return String.valueOf(cbuf, 0, cpos); } public final char[] nextCharArray() throws IOException { return readToken(); } public final int nextInt() throws IOException { if (!hasRemaining()) return 0; int value = 0; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return value; } public final long nextLong() throws IOException { if (!hasRemaining()) return 0L; long value = 0L; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return value; } public final char nextChar() throws IOException { if (!hasRemaining()) throw new EOFException(); final char c = (char) buf[pos++]; if (hasRemaining() && buf[pos++] == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return c; } public final float nextFloat() throws IOException { return Float.parseFloat(next()); } public final double nextDouble() throws IOException { return Double.parseDouble(next()); } public final boolean[] nextBooleanArray(char ok) throws IOException { char[] s = readToken(); int n = s.length; boolean[] t = new boolean[n]; for (int i = 0; i < n; i++) t[i] = s[i] == ok; return t; } public final boolean[][] nextBooleanMatrix(int h, int w, char ok) throws IOException { boolean[][] s = new boolean[h][]; for (int i = 0; i < h; i++) { char[] t = readToken(); int n = t.length; s[i] = new boolean[n]; for (int j = 0; j < n; j++) s[i][j] = t[j] == ok; } return s; } public final String[] nextStringArray(int len) throws IOException { String[] arr = new String[len]; for (int i = 0; i < len; i++) arr[i] = next(); return arr; } public final int[] nextIntArray(int len) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = nextInt(); return arr; } public final int[] nextIntArray(int len, java.util.function.IntUnaryOperator map) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsInt(nextInt()); return arr; } public final long[] nextLongArray(int len, java.util.function.LongUnaryOperator map) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsLong(nextLong()); return arr; } public final int[][] nextIntMatrix(int h, int w) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextInt(); return arr; } public final int[][] nextIntMatrix(int h, int w, java.util.function.IntUnaryOperator map) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = map.applyAsInt(nextInt()); return arr; } public final long[] nextLongArray(int len) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = nextLong(); return arr; } public final long[][] nextLongMatrix(int h, int w) throws IOException { long[][] arr = new long[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextLong(); return arr; } public final float[] nextFloatArray(int len) throws IOException { float[] arr = new float[len]; for (int i = 0; i < len; i++) arr[i] = nextFloat(); return arr; } public final double[] nextDoubleArray(int len) throws IOException { double[] arr = new double[len]; for (int i = 0; i < len; i++) arr[i] = nextDouble(); return arr; } public final char[][] nextCharMatrix(int h, int w) throws IOException { char[][] arr = new char[h][]; for (int i = 0; i < h; i++) arr[i] = readToken(); return arr; } public final void nextThrow() throws IOException { next(); return; } public final void nextThrow(int n) throws IOException { for (int i = 0; i < n; i++) nextThrow(); return; } } final class ContestOutputStream extends FilterOutputStream implements Appendable { protected final byte[] buf; protected int pos = 0; public ContestOutputStream() { super(System.out); this.buf = new byte[1 << 13]; } @Override public void flush() throws IOException { out.write(buf, 0, pos); pos = 0; out.flush(); } void put(byte b) throws IOException { if (pos >= buf.length) flush(); buf[pos++] = b; } int remaining() throws IOException { if (pos >= buf.length) flush(); return buf.length - pos; } @Override public void write(int b) throws IOException { put((byte) b); } @Override public void write(byte[] b, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = b[o + i]; pos += rem; o += rem; l -= rem; } } @Override public ContestOutputStream append(char c) throws IOException { put((byte) c); return this; } @Override public ContestOutputStream append(CharSequence csq, int start, int end) throws IOException { int off = start; int len = end - start; while (len > 0) { int rem = Math.min(remaining(), len); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) csq.charAt(off + i); pos += rem; off += rem; len -= rem; } return this; } @Override public ContestOutputStream append(CharSequence csq) throws IOException { return append(csq, 0, csq.length()); } public ContestOutputStream append(char[] arr, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) arr[o + i]; pos += rem; o += rem; l -= rem; } return this; } public ContestOutputStream print(char[] arr) throws IOException { return append(arr, 0, arr.length).newLine(); } public ContestOutputStream print(boolean value) throws IOException { if (value) return append("o"); return append("x"); } public ContestOutputStream println(boolean value) throws IOException { if (value) return append("o\n"); return append("x\n"); } public ContestOutputStream print(boolean[][] value) throws IOException { final int n = value.length, m = value[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) print(value[i][j]); newLine(); } return this; } public ContestOutputStream print(int value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(int value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(long value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(long value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(float value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(float value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(double value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(double value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(char value) throws IOException { return append(value); } public ContestOutputStream println(char value) throws IOException { return append(value).newLine(); } public ContestOutputStream print(String value) throws IOException { return append(value); } public ContestOutputStream println(String value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(Object value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(Object value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream printYN(boolean yes) throws IOException { if (yes) return println("Yes"); return println("No"); } public ContestOutputStream printAB(boolean yes) throws IOException { if (yes) return println("Alice"); return println("Bob"); } public ContestOutputStream print(CharSequence[] arr) throws IOException { if (arr.length > 0) { append(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').append(arr[i]); } return this; } public ContestOutputStream print(int[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(int[] arr, int length) throws IOException { if (length > 0) print(arr[0]); for (int i = 1; i < length; i++) append('\u0020').print(arr[i]); newLine(); return this; } public ContestOutputStream println(int[] arr) throws IOException { for (int i : arr) print(i).newLine(); return this; } public ContestOutputStream println(int[] arr, int length) throws IOException { for (int i = 0; i < length; i++) println(arr[i]); return this; } public ContestOutputStream print(boolean[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(long[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(long[] arr, int length) throws IOException { if (length > 0) print(arr[0]); for (int i = 1; i < length; i++) append('\u0020').print(arr[i]); newLine(); return this; } public ContestOutputStream println(long[] arr, int length) throws IOException { for (int i = 0; i < length; i++) println(arr[i]); return this; } public ContestOutputStream println(long[] arr) throws IOException { for (long i : arr) print(i).newLine(); return this; } public ContestOutputStream print(float[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream println(float[] arr) throws IOException { for (float i : arr) print(i).newLine(); return this; } public ContestOutputStream print(double[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return newLine(); } public ContestOutputStream println(double[] arr) throws IOException { for (double i : arr) print(i).newLine(); return this; } public ContestOutputStream print(Object[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return newLine(); } public ContestOutputStream print(java.util.ArrayList<?> arr) throws IOException { if (!arr.isEmpty()) { final int n = arr.size(); print(arr.get(0)); for (int i = 1; i < n; i++) print(" ").print(arr.get(i)); } return newLine(); } public ContestOutputStream println(java.util.ArrayList<?> arr) throws IOException { final int n = arr.size(); for (int i = 0; i < n; i++) println(arr.get(i)); return this; } public ContestOutputStream println(Object[] arr) throws IOException { for (Object i : arr) print(i).newLine(); return this; } public ContestOutputStream newLine() throws IOException { return append(System.lineSeparator()); } public ContestOutputStream endl() throws IOException { newLine().flush(); return this; } public ContestOutputStream print(int[][] arr) throws IOException { for (int[] i : arr) print(i); return this; } public ContestOutputStream print(long[][] arr) throws IOException { for (long[] i : arr) print(i); return this; } public ContestOutputStream print(char[][] arr) throws IOException { for (char[] i : arr) print(i); return this; } public ContestOutputStream print(Object[][] arr) throws IOException { for (Object[] i : arr) print(i); return this; } public ContestOutputStream println() throws IOException { return newLine(); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 11
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
3a7c8686625a00a507501bd03afe3a4a
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class RoundEdu136D { 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))); // the code for the deep recursion (more than 100k or 3~400k or so) // Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28); // t.start(); // t.join(); RoundEdu136D sol = new RoundEdu136D(); 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), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ... int n, k; int[] p; final int ROOT = 0; void getInput() { n = in.nextInt(); k = in.nextInt(); p = new int[n]; p[ROOT] = -1; for(int i=1; i<n; i++) p[i] = in.nextInt()-1; } void printOutput() { out.printlnAns(ans); } int ans; void solve(){ // if depth[u] = x // then for all descendant v of u, depth[v] -= x-1 int maxDepth = 0; int[] depth = new int[n]; for(int i=1; i<n; i++) { depth[i] = depth[p[i]]+1; maxDepth = Math.max(maxDepth, depth[i]); } ArrayList<Integer>[] children = new ArrayList[n]; for(int i=0; i<n; i++) children[i] = new ArrayList<Integer>(); for(int i=1; i<n; i++) children[p[i]].add(i); ArrayList<Integer>[] depthToVertex = new ArrayList[n]; for(int i=0; i<n; i++) depthToVertex[i] = new ArrayList<Integer>(); for(int i=0; i<n; i++) depthToVertex[depth[i]].add(i); int lo = 1; int hi = maxDepth; while(lo < hi) { int mid = (lo+hi)/2; int cost = 0; // int curr = maxDepth - mid + 1; // while(curr > mid) { // cost += depthToVertex[curr].size(); // curr -= mid; // } ArrayList<Integer> queue = new ArrayList<Integer>(); for(int i=1; i<n; i++) if(depth[i] > mid) queue.add(i); Collections.sort(queue, (i, j) -> Integer.compare(depth[j], depth[i])); boolean[] visited = new boolean[n]; for(int curr: queue) { if(visited[curr]) continue; for(int i=0; i<mid-1; i++) curr = p[curr]; ArrayList<Integer> q = new ArrayList<Integer>(); int dist = 1; q.add(curr); while(dist <= mid) { ArrayList<Integer> qNext = new ArrayList<>(); for(int v: q) { if(visited[v]) continue; visited[v] = true; for(int child: children[v]) qNext.add(child); } dist++; q = qNext; } cost++; } if(cost <= k) hi = mid; else lo = mid+1; } ans = lo; } // Optional<T> solve() // return Optional.empty(); 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 <T> void printlnAns(Optional<T> ans) { // if(ans.isEmpty()) // println(-1); // else // printlnAns(ans.get()); // } public void printlnAns(OptionalInt ans) { println(ans.orElse(-1)); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean[] ans) { for(boolean b: ans) printlnAns(b); } 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
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
b086051e25c8dea609904cd114c8cc4f
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; public class User { static int ans; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String [] line = br.readLine().split(" "); int t = Integer.parseInt(line[0]); for(int i = 0; i < t; i++) { line = br.readLine().split(" "); int n = Integer.parseInt(line[0]), k = Integer.parseInt(line[1]); List<List<Integer>> adjList = new ArrayList<>(); for(int j = 0; j < n+1; j++) adjList.add(new ArrayList<>()); line = br.readLine().split(" "); for(int j = 0; j < line.length; j++){ adjList.get(Integer.parseInt(line[j])).add(2+j); } showResult(adjList, n, k); } br.close(); } //check static void showResult(List<List<Integer>> adj, int n, int k) { int left = 1, right = n, best = n; while(left <= right){ int mid = (left + right)/2; boolean canDo = check(mid, adj, k); if(canDo){best = mid; right = mid - 1;} else {left = mid + 1;} } System.out.println(best); } static boolean check(int mid, List<List<Integer>> adj, int k){ ans = 0; if(mid > 1) { dfs(mid, adj, 1, -1); return ans <= k; } else return adj.size() - 2 - adj.get(1).size() <= k; } static int dfs(int mid, List<List<Integer>> adj, int root, int par){ int size = 1; for(int child : adj.get(root)){ size = Math.max(dfs(mid, adj, child, root)+1, size); } if(size == mid && par != 1 && root != 1){ ans++; return 0; } return size; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
cb03403d58a5c41640fadaff9d49cb39
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.util.*; import java.io.*; public class User { static int ans; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String [] line = br.readLine().split(" "); int t = Integer.parseInt(line[0]); for(int i = 0; i < t; i++) { line = br.readLine().split(" "); int n = Integer.parseInt(line[0]), k = Integer.parseInt(line[1]); List<List<Integer>> adjList = new ArrayList<>(); for(int j = 0; j < n+1; j++) adjList.add(new ArrayList<>()); line = br.readLine().split(" "); for(int j = 0; j < line.length; j++){ adjList.get(Integer.parseInt(line[j])).add(2+j); } showResult(adjList, n, k); } br.close(); } static void showResult(List<List<Integer>> adj, int n, int k) { int left = 1, right = n, best = n; while(left <= right){ int mid = (left + right)/2; boolean canDo = check(mid, adj, k); if(canDo){best = mid; right = mid - 1;} else {left = mid + 1;} } System.out.println(best); } static boolean check(int mid, List<List<Integer>> adj, int k){ ans = 0; if(mid > 1) { dfs(mid, adj, 1, -1); return ans <= k; } else return adj.size() - 2 - adj.get(1).size() <= k; } static int dfs(int mid, List<List<Integer>> adj, int root, int par){ int size = 1; for(int child : adj.get(root)){ size = Math.max(dfs(mid, adj, child, root)+1, size); } if(size == mid && par != 1 && root != 1){ ans++; return 0; } return size; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
d71f6abcf4a0e21ccef39d27bbbb059f
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),k=Integer.parseInt(s[1]); ArrayList<Integer> g[]=new ArrayList[n]; int i; for(i=0;i<n;i++) g[i]=new ArrayList<>(); s=bu.readLine().split(" "); for(i=1;i<n;i++) { int p=Integer.parseInt(s[i-1])-1; g[p].add(i); } int l=1,r=n,mid,ans=r,d[]=new int[n]; while(l<=r) { mid=(l+r)>>1; int moves=dfs(g,0,-1,d,mid); if(moves<=k) { ans=mid; r=mid-1; } else l=mid+1; } sb.append(ans+"\n"); } System.out.print(sb); } static int dfs(ArrayList<Integer> g[],int n,int p,int d[],int max) { int del=0; d[n]=0; for(int x:g[n]) if(x!=p) { del+=dfs(g,x,n,d,max); d[n]=Math.max(d[n],d[x]+1); } if(p!=0 && n!=0 && d[n]==max-1) {del++; d[n]=-1;} //System.out.print(max+" "+n+" "+d[n]+" "+del+"\n"); return del; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
fc973bd622978fa40dcb5a92b3aa4fca
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import static java.lang.Math.max; public class Main { static FastReader fastReader = new FastReader(); public static void main(String[] args) { int t = fastReader.nextInt(); int x = 1; while (x++ <= t) { String s = solve(); System.out.println(s); } } static int m = 0; private static String solve() { int n = fastReader.nextInt(); int k = fastReader.nextInt(); int[] parent = new int[n + 1]; ArrayList<Integer>[] graph = new ArrayList[n + 1]; for(int i = 1 ; i <= n ; i++) graph[i] = new ArrayList<>(); for(int i = 2 ; i <= n ; i++){ parent[i] = fastReader.nextInt(); graph[i].add(parent[i]); graph[parent[i]].add(i); } int l = 1, h = n; int ans = h; while(l <= h){ int mid = (l + h) / 2; boolean check = check(graph, mid, k); if(check){ ans = mid; h = mid - 1; }else{ l = mid + 1; } } return String.valueOf(ans); } private static int dfs(ArrayList<Integer>[] graph, int mid, int ver, int par) { int h = 1; for(int nbr : graph[ver]){ if(nbr == par) continue; h = max(dfs(graph, mid, nbr, ver) + 1, h); } if(h == mid && ver != 1 && par != 1){ m++; return 0; } return h; } private static boolean check(ArrayList<Integer>[] graph, int mid, int k) { m = 0; if(mid > 1){ dfs(graph, mid, 1, 0); }else{ m = graph.length - graph[1].size() - 2; } return m <= k; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class ModuloArithmetic { /* if a % mod == b % mod a^k % mod == b ^ k % mod eg 29 ^ 5 mod 3 ? 29 % 3 = 2 2 ^ 5 % 3 = 2 == 29 ^ 5 % 3 */ public static long moduloSubtraction(long a, long b, long mod) { if (a >= b) return (a - b) % mod; return (mod - (a - b)) % mod; } public static long moduloDivide(long a, long b, long mod) { a = a % mod; long inv = moduloInverse(b, mod); if (inv == -1) return -1; return ((inv * a) % mod); } public static long moduloExponentiation(long num, long pow, long mod) { num = num % mod; long res = 1; while (pow > 0) { if ((pow & 1) == 1) { res = res * num % mod; } num = num * num % mod; pow >>= 1; } return res; } // TC : log(a) public static long multiplyTwoNumbers(long a, long b, long mod) { long res = 0; while (a > 0) { if ((a & 1) == 1) { res = (res + b) % mod; } b = (b * 2) % mod; // multiply b by 2 and a getting half after each iteration a >>= 1; } return res; } /* ----------------- Modulo Inverse ---------------------------- TC : O(log ab) (a * inverse(a)) % mod = 1 for modulo multiplicative inverse exist for a N under P than GCD(N, P) = 1 */ public static long moduloInverse(long num, long mod) { long[] coff = new long[2]; long gcd = MathsBasic.extendedEuclid(num, mod, coff); if (gcd != 1) { return 0; // No inverse exist } else { long inverse = (coff[0] % mod + mod) % mod; return inverse; } } // Fermat Little Theorem // a ^(m - 1) % mod == 1 if a & m (m is a prime number) are co - prime (GCD(a, m) == 1) // modulo inverse of a is a ^ (m - 2) public static long moduloInverse2(long num, long mod) { return moduloExponentiation(num, mod - 2, mod); } public static long binomialCoefficient(int n, int k, long mod) { return factorial[n] * moduloInverse(factorial[k] * factorial[n - k] % mod, mod) % mod; } static long[] factorial = new long[(int) 1e9]; public static void factorials(long MAXN, long mod) { for (int i = 1; i <= MAXN; i++) { factorial[i] = factorial[i - 1] * i % mod; } } } class MathsBasic { /* --------------------- GCD --------------------------- TC : O(log ab) */ public static long gcd(long a, long b) { return a == 0 ? b : gcd(b % a, a); } /* Can we find the numbers x, y such that ax + by = gcd(a, b) There exists infinitely many pairs - this is Bezout's Lemma . The algorithm to generate such pairs is called Extended Euclidean Algorithm. */ /* ------------ Power of 2 ----------------- */ public static boolean isPowerOfTwo(long x) { /* First x in the below expression is for the case when x is 0 */ return x != 0 && ((x & (x - 1)) == 0); } /* --------------------- Binary Exponentiation ------------------ TC : O(log(n)) */ public static long binPow(long num, long pow) { long res = 1; while (pow > 0) { if ((pow & 1) == 1) { res = res * num; } num = num * num; pow >>= 1; } return res; } /* --------- Apply k Permutations on a sequence ------------ TC : nLog(k) */ private static long[] permute(long[] sequence, long[] permutation, long k) { while (k > 0) { if ((k & 1) == 1) { sequence = applyPermute(sequence, permutation); } permutation = applyPermute(permutation, permutation); k >>= 1; } return sequence; } private static long[] applyPermute(long[] sequence, long[] permutation) { long[] newSequence = new long[sequence.length]; for (int i = 1; i < sequence.length; i++) { newSequence[i] = sequence[(int) permutation[i]]; // newSequence[permutation[i]] = sequence[i]; Acc. to given Question } return newSequence; } /* -------------- Extended Euclid Theorem ---------------------- TC : O(Log(ab)) ax + by = gcd(a, b) */ public static long extendedEuclid(long a, long b, long[] coff) { if (b == 0) { long gcd = a; coff[0] = 1; coff[1] = 0; return gcd; } long gcd = extendedEuclid(b, a % b, coff); long x = coff[1]; long y = coff[0] - coff[1] * (a / b); coff[0] = x; coff[1] = y; return gcd; // iterative code // long x = 0, y = 1, lastx = 1, lasty = 0, temp; // while (b != 0) // { // long q = a / b; // long r = a % b; // // a = b; // b = r; // // temp = x; // x = lastx - q * x; // lastx = temp; // // temp = y; // y = lasty - q * y; // lasty = temp; // } // coff[0] = lastx; // coff[1] = lasty; // return a; } /* ------------------------ Prime Factorization ------------------------- TC : O(sqrt(N)) */ public static ArrayList<int[]> primeFactorization(long num) { ArrayList<int[]> factors = new ArrayList<>(); for (int i = 2; (long) i * i <= num; i++) { if (num % i == 0) { int count = 0; while (num % i == 0) { count++; num = num / i; } factors.add(new int[]{i, count}); } } if (num > 1) factors.add(new int[]{(int) num, 1}); return factors; } // Prime Factorization using Sieve // TC : log(N) public static ArrayList<int[]> primeFactorizationSieve(int num) { ArrayList<int[]> factors = new ArrayList<>(); int[] arr = new int[(int) (num + 1)]; for (int i = 2; i <= num; i++) { if (arr[i] == 0) { for (int j = i; j <= num; j += i) { if (arr[j] == 0) arr[j] = i; } } } while (num != 1) { int x = arr[num]; num = num / x; int count = 1; while (arr[num] == x) { count++; num = num / x; } factors.add(new int[]{x, count}); } return factors; } /* ----------------------------------Matrix Functions---------------------------------- ` TC : O(N ^ 3 * Log(N)) */ public static int[][] identityMatrix(int n) { int[][] idm = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) idm[i][j] = 1; else idm[i][j] = 0; } } return idm; } public static int[][] matrixMultiplication(int[][] A, int[][] B, int n) { int[][] res = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { res[i][j] = 0; for (int k = 0; k < n; k++) res[i][j] += A[i][k] * B[k][j]; } } return res; } public static int[][] matrixExponentiation(int[][] matrix, int pow) { int n = matrix.length; int[][] I = identityMatrix(n); while (pow > 0) { if ((pow & 1) == 1) { I = matrixMultiplication(I, matrix, n); } matrix = matrixMultiplication(matrix, matrix, n); pow >>= 1; } return I; } /* ------------------- nth element of Recurrence Relation ----------------------- Magic matrix = [A B] for Fn = xF(n - 1) + yF(n - 2) [C D] for nth number [F(1) F(2)] * ([A B] ^ (n - 1)) = [F(n) F(n - 1)] [C D] [F(1) F(2)] * [0 1] = [F(2) F(3)] [1 1] if F(n) depends on k terms than magic matrix of order k * k and previous matrix of k */ public static int getFibN(int[] ar, int n) { if (n <= 2) return ar[n]; int[][] magicMatrix = {{0, 1}, {1, 1}}; magicMatrix = matrixExponentiation(magicMatrix, n - 1); int Fn = (int) ((ar[1] * magicMatrix[0][0] + ar[2] * magicMatrix[2][1]) % (1e9 + 7)); return Fn; } /* --------------------- Euler's Totient Function -------------------- counts the number of positive integers upto n which are co - prime with n Phi(n) = # +ve integers co - prime with n Phi(PrimeNo) = PrimeNo - 1 Phi(PrimeNo ^ x ) = PrimeNo ^ (x - 1)(PrimeNo - 1) Phi(N) = Phi(P1^x1 * p2^x2 * P3^x3 ...) = Phi(P1^x1)*Phi(P2^x2)*Phi(P3^x3)..... = P1^(x1 - 1)(P1 - 1)*P2^(x2 - 1)(P2 - 1)............ = N*((P1 - 1)/P1)*((P2 - 1)/P2)*...... */ // TC : O(sqrt(N)) public static int eulerTotientFunction(int n) { ArrayList<int[]> primeFactors = primeFactorization(n); int res = n; for (int[] x : primeFactors) { res /= x[0]; res *= (x[0] - 1); } return res; } //O(Nlog(log(N)) public static int[] eulerTotientFunctionTillNUsingSieve(int n) { int[] phis = new int[n + 1]; for (int i = 1; i <= n; i++) phis[i] = i; for (int i = 2; i <= n; i++) { if (phis[i] == i) { for (int j = i; j <= n; j += i) { phis[j] /= i; phis[j] *= (i - 1); } } } return phis; } /* GCD and Euler Totient Function Relation for ans = sum of GCD(i, N) for i = 1 to N Brute force TC : O(Q * NLog(N)) for q queries optimized TC : O(Q * Sqrt(N)) Observation 1 : GCD(i, N) = one of the divisors of N Observation 2 : Instead of Running the loop from 1 to N, We can check for each divisor d of N how many numbers i are there with GCD(i, N) = d for N = 12 ans = (1) * 4 GCD(x, n) = d GCD(x/d, n/d) = 1 so ETF of n/d gives no. of integers form 1 to n whose GCD with n is d this is how we use get count */ public static int GCDAndETF(int n) { int res = 0; int[] phis = eulerTotientFunctionTillNUsingSieve(n); for (int i = 1; i * i <= n; i++) { if (n % i == 0) { int d1 = i; int d2 = n / i; res += d1 * phis[n / d1]; // getCount(d1, n) if (d1 != d2) res += d2 * phis[n / d2]; // getCount(d2, n) } } return res; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
2a007364fd060a533cbb4f1bbe4d2bdb
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { public static void main(String[]args) throws IOException { new Main().run(); } File input=new File("D:\\test\\input.txt"); void run() throws IOException{ // new solve().setIO(input, System.out).run(); new solve().setIO(System.in,System.out).run(); } class solve extends ioTask{ // StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // int in() throws IOException { // st.nextToken(); // return (int)st.nval; // } // long inl() throws IOException { // st.nextToken(); // return (long)st.nval; // } // double ind()throws IOException { // st.nextToken(); // return st.nval; // } // String ins() throws IOException { // st.nextToken(); // return st.sval; // } int t,n,k,pre,len,now,r,i,j; void run()throws IOException{ t=in.in(); while(t-->0) { n=in.in(); k=in.in(); int[]p=new int[n]; for(int i=1;i<n;i++) { p[i]=in.in()-1; } int l=0,r=n-1; while(r-l>1) { int x=(l+r)>>1; int step=0; int[]h=new int[n]; for(int i=n-1;i>0;i--) { if(h[i]==x-1&&p[i]!=0) { step++; }else { h[p[i]]=Math.max(h[p[i]],h[i]+1); } } if(step<=k) { r=x; }else { l=x; } } out.println(r); } out.close(); } } class Graph{ int[]to,nxt,head; // int[]w; int cnt; private int st=1; void init(int n) { cnt=st; Arrays.fill(head, 1,n+1,0); } public Graph(){} public Graph(int n,int m) { to=new int[m+1]; nxt=new int[m+1]; head=new int[n+1]; // w=new int[m+1]; cnt=st; } void add(int u,int v) { to[cnt]=v; nxt[cnt]=head[u]; // w[cnt]=l; head[u]=cnt++; } Graph copy() { Graph g=new Graph(); g.to=to.clone(); g.head=head.clone(); g.nxt=nxt.clone(); // g.w=w.clone(); g.cnt=cnt; return g; } void show(int n){ for(int u=1,v;u<=n;u++){ for(int j=head[u];j>0;j=nxt[j]){ v=to[j]; if(u<v) { System.out.printf("%-4d%-4d%-4d\n",u,v // ,w[j] ); } } } } } class In{ private StringTokenizer in=new StringTokenizer(""); private InputStream is; private BufferedReader bf; public In(File file) throws IOException { is=new FileInputStream(file); init(); } public In(InputStream is) throws IOException { this.is=is; init(); } private void init() throws IOException { bf=new BufferedReader(new InputStreamReader(is)); } boolean hasNext() throws IOException { return in.hasMoreTokens()||bf.ready(); } String ins() throws IOException { while(!in.hasMoreTokens()) { in=new StringTokenizer(bf.readLine()); } return in.nextToken(); } int in() throws IOException { return Integer.parseInt(ins()); } long inl() throws IOException { return Long.parseLong(ins()); } double ind() throws IOException { return Double.parseDouble(ins()); } String line() throws IOException { return bf.readLine(); } } class Out{ PrintWriter out; private OutputStream os; private void init() { out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(os))); } public Out(File file) throws IOException { os=new FileOutputStream(file); init(); } public Out(OutputStream os) throws IOException { this.os=os; init(); } } abstract class ioTask{ In in; PrintWriter out; public ioTask setIO(File in,File out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } public ioTask setIO(File in,OutputStream out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } public ioTask setIO(InputStream in,OutputStream out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } public ioTask setIO(InputStream in,File out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } void run()throws IOException{ } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
313fdd8f637ebcf46bfdc2e335117626
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import static java.lang.Math.*; public class D { public Object solve () { int N = sc.nextInt(), K = sc.nextInt(); int [] P = dec(sc.nextInts()); int [][] E = new int [N-1][]; for (int i : rep(N-1)) E[i] = new int [] { P[i], i+1 }; G = dgraph(N, E); H = new boolean [N]; H[0] = true; for (int i : G[0]) H[i] = true; int p = 0, q = N; while (q - p > 1) { int m = (p + q) / 2; int c = dfs(0, m)[0]; if (c <= K) q = m; else p = m; } return q; } int [][] G; boolean [] H; int [] dfs (int i, int m) { int c = 0, d = 1; for (int j : G[i]) { int [] r = dfs(j, m); c += r[0]; d = max(d, 1 + r[1]); } if (!H[i] && d >= m) { d = 0; ++c; } int [] res = { c, d }; return res; } private static final int CONTEST_TYPE = 2; private static void init () { } private static int [] dec (int ... A) { for (int i = 0; i < A.length; ++i) --A[i]; return A; } private static int [][] dgraph (int N, int [][] E) { return dwgraph(N, E)[0]; } private static int [][][] dwgraph (int N, int [][] E) { int [] D = new int [N]; for (int [] e : E) ++D[e[0]]; int [][][] res = new int [2][N][]; for (int i = 0; i < 2; ++i) for (int j = 0; j < N; ++j) res[i][j] = new int [D[j]]; D = new int [N]; for (int [] e : E) { int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1; res[0][x][D[x]] = y; res[1][x][D[x]] = z; ++D[x]; } return res; } private static int [] rep (int N) { return rep(0, N); } private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static class IOUtils { public static class MyScanner { public String next () { newLine(); return line[index++]; } public int nextInt () { return Integer.parseInt(next()); } public String nextLine () { line = null; return readLine(); } public String [] nextStrings () { return split(nextLine()); } public int [] nextInts () { String [] S = nextStrings(); int N = S.length; int [] res = new int [N]; for (int i = 0; i < N; ++i) res[i] = Integer.parseInt(S[i]); return res; } ////////////////////////////////////////////// private boolean eol () { return index == line.length; } private String readLine () { try { int b; StringBuilder res = new StringBuilder(); while ((b = System.in.read()) < ' ') continue; res.append((char)b); while ((b = System.in.read()) >= ' ') res.append((char)b); return res.toString(); } catch (Exception e) { throw new Error (e); } } private MyScanner () { try { while (System.in.available() == 0) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine () { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim (String delim, Object o, Object ... A) { java.util.List<String> str = new java.util.ArrayList<>(); append(str, o); for (Object p : A) append(str, p); return String.join(delim, str.toArray(new String [0])); } ////////////////////////////////////////////////////////////////////////////////// private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start () { if (t == 0) t = millis(); } private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append (java.util.List<String> str, Object o) { append(x -> append(str, x), x -> str.add(x.toString()), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void flush () { pw.flush(); System.out.flush(); } private static void print (Object o, Object ... A) { String res = build(o, A); if (DEBUG == 0) { String out = res.split(System.lineSeparator())[0]; if (out.length() > 80) out = out.substring(0, 80); if (out.length() < res.length()) out += " ..."; err(out, '(', time(), ')'); } if (DEBUG == 2) err(res, '(', time(), ')'); if (res.length() > 0) pw.println(res); if (DEBUG == 1) flush(); } private static void err (Object o, Object ... A) { System.err.println(build(o, A)); } private static int DEBUG = -1; private static void exit () { String end = "------------------" + System.lineSeparator() + time(); switch(DEBUG) { case 1: print(end); break; case 0: case 2: err(end); break; } IOUtils.pw.close(); System.out.flush(); System.exit(0); } private static long t; private static long millis () { return System.currentTimeMillis(); } private static String time () { return "Time: " + (millis() - t) / 1000.0; } private static void run (int N) { try { DEBUG = Integer.parseInt(System.getProperty("DEBUG")); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new D().solve(); if (res != null) { @SuppressWarnings("all") Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res; print(o); } } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { @SuppressWarnings("all") int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt(); init(); IOUtils.run(N); } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
c317a880f287905bd2aecb04462f01bd
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.sql.Array; import java.util.*; import java.io.*; import java.math.BigInteger; import java.util.stream.IntStream; import java.util.stream.LongStream; public class Main { public static FastReader cin; public static PrintWriter out; public static long MOD = 998244353L; public static long[][] C = new long[1001][1001]; public static int[] par,depth; public static ArrayList<Integer>[] son; public static int cnt = 0; public static int n,k; public static void main(String[] args) throws Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); cin = new FastReader(); int ttt = cin.nextInt(); for(int qqq = 0; qqq < ttt; qqq++){ n = cin.nextInt(); k = cin.nextInt(); son = new ArrayList[n + 1]; Arrays.setAll(son,e -> new ArrayList<>()); par = new int [n + 1]; depth = new int[n + 1]; par[1] = 1; for(int i = 2; i <= n; i++){ par[i] = cin.nextInt(); son[par[i]].add(i); } ArrayDeque<Integer>deque = new ArrayDeque<>(); int nowDepth = 0; deque.add(1); while(!deque.isEmpty()){ int size = deque.size(); for(int i = 0; i < size; i++){ int nextIndex = deque.poll(); depth[nextIndex] = nowDepth; ArrayList<Integer>temp = son[nextIndex]; for(int j = 0; j < temp.size(); j++){ deque.add(temp.get(j)); } } nowDepth++; } int L = 1; int R = n; int ans = L; while(L < R){ int mid = (L + R)>> 1; if (check(mid)){ R = mid; ans = mid; } else{ L = mid + 1; } } // out.println("check(2)="+check(2)); // out.println("check(1)="+check(1)); out.println(ans); } out.close(); } public static boolean check(int mid){ cnt = 0; dfs(1,0,mid); return cnt <= k; } public static int dfs(int now,int father,int h){ int maxDepth = 0; for(Integer next:son[now]){ maxDepth = Math.max(maxDepth,dfs(next,now,h)); } maxDepth++; if(par[now] == 1 || now == 1)return 0; if(maxDepth >= h){ cnt++; return 0; }else{ return maxDepth; } } public static long lcm(long a,long b ){ long ans = a / gcd(a,b) * b ; return ans; } public static long gcd(long a,long b){ if(b==0)return a; else return gcd(b,a%b); } static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
c58974303fd9eb20c193a2042addec7c
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),k=Integer.parseInt(s[1]); ArrayList<Integer> g[]=new ArrayList[n]; int i; for(i=0;i<n;i++) g[i]=new ArrayList<>(); s=bu.readLine().split(" "); for(i=1;i<n;i++) { int p=Integer.parseInt(s[i-1])-1; g[p].add(i); } int l=1,r=n,mid,ans=r,d[]=new int[n]; while(l<=r) { mid=(l+r)>>1; int moves=dfs(g,0,-1,d,mid); if(moves<=k) { ans=mid; r=mid-1; } else l=mid+1; } sb.append(ans+"\n"); } System.out.print(sb); } static int dfs(ArrayList<Integer> g[],int n,int p,int d[],int max) { int del=0; d[n]=0; for(int x:g[n]) if(x!=p) { del+=dfs(g,x,n,d,max); d[n]=Math.max(d[n],d[x]+1); } if(p!=0 && n!=0 && d[n]==max-1) {del++; d[n]=-1;} //System.out.print(max+" "+n+" "+d[n]+" "+del+"\n"); return del; } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
14932c5b927d41eeff07fcb7b7a29915
train_109.jsonl
1664462100
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
256 megabytes
import java.io.*; import java.util.*; public class CF1739D extends PrintWriter { CF1739D() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; byte[] bb = new byte[1 << 15]; int i, n; byte getc() { if (i == n) { i = n = 0; try { n = in.read(bb); } catch (IOException e) {} } return i < n ? bb[i++] : 0; } int nextInt() { byte c = 0; while (c <= ' ') c = getc(); int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); } return a; } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1739D o = new CF1739D(); o.main(); o.flush(); } int[] eo; int[][] ej; void append(int i, int j) { int o = eo[i]++; if (o >= 2 && (o & o - 1) == 0) ej[i] = Arrays.copyOf(ej[i], o << 1); ej[i][o] = j; } int[] dd_, qu; int solve(int n, int d_) { int[] dd = Arrays.copyOf(dd_, n + 1); int ans = 0; for (int h = n - 1; h > 0; h--) { int i = qu[h]; int d = dd[i]; for (int o = eo[i]; o-- > 0; ) { int j = ej[i][o]; d = Math.max(d, dd[j]); } if (dd[i] > 1 && d - dd[i] + 1 == d_) { ans++; dd[i] = 0; } else dd[i] = d; } return ans; } void main() { for (int t = sc.nextInt(); t-- > 0; ) { int n = sc.nextInt(); int k = sc.nextInt(); eo = new int[n + 1]; ej = new int[n + 1][2]; for (int i = 2; i <= n; i++) { int p = sc.nextInt(); append(p, i); } dd_ = new int[n + 1]; qu = new int[n]; int cnt = 0; qu[cnt++] = 1; for (int h = 0; h < cnt; h++) { int i = qu[h]; int d = dd_[i] + 1; for (int o = eo[i]; o-- > 0; ) { int j = ej[i][o]; dd_[j] = d; qu[cnt++] = j; } } int lower = 0, upper = n - 1; while (upper - lower > 1) { int d = (lower + upper) / 2; if (solve(n, d) <= k) upper = d; else lower = d; } println(upper); } } }
Java
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
4 seconds
["2\n1\n5\n3\n1"]
null
Java 17
standard input
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
f260d0885319a146904b43f89e253f0c
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
1,900
For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
standard output
PASSED
e4fe1acd2230a6ed154739b1d54fc3cf
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
/* Goal: Become better in CP! Key: Consistency and Discipline Desire: SDE @ Google USA Motto: Do what i Love <=> Love what i do If you don't use your brain 100%, it deteriorates gradually */ import java.util.*; import java.io.*; import java.math.*; public class Solution { static StringBuffer str=new StringBuffer(); static BufferedReader bf; static PrintWriter pw; static int n; static long mod=998244353l; static int MAXN=61; static long[][] comb = new long[MAXN][MAXN]; static long dp[][]; static void pre(){ comb[0][0] = 1; for (int i = 1; i < MAXN; i++) { comb[i][0] = 1; for (int j = 1; j <= i; j++) { comb[i][j] = (comb[i-1][j] + comb[i-1][j-1]) % mod; } } } static long solve(int n){ if(n<=0) return 0; // alex has card n and boris has card n-1 long v1=(n-1>=n/2-1 && n>=1 && n/2>=1)?comb[n-1][n/2-1]:0; // alex has card n-1 and boris has card n // alex has both n-2 and n-3 long v2=(n-4>=n/2-1 && n>=4 && n/2-1>=0)?comb[n-4][n/2-1]:0; // alex makes it a draw long v3=solve(n-4); return ((v1+v2+v3)%mod + mod)%mod; } public static void main(String[] args) throws java.lang.Exception { boolean lenv=false; int te=1; 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)); } pre(); int q1 = Integer.parseInt(bf.readLine().trim()); for(te=1;te<=q1;te++) { n=Integer.parseInt(bf.readLine().trim()); long alex=solve(n); long draw=1; long bob=(comb[n][n/2]-alex-draw+mod)%mod; str.append(alex).append(" ").append(bob).append(" ").append(draw).append("\n"); } pw.print(str); pw.flush(); // System.out.println(str); } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
cf039486867e67a51b948e84791842a2
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
/* Goal: Become better in CP! Key: Consistency and Discipline Desire: SDE @ Google USA Motto: Do what i Love <=> Love what i do If you don't use your brain 100%, it deteriorates gradually */ import java.util.*; import java.io.*; import java.math.*; public class Solution { static StringBuffer str=new StringBuffer(); static BufferedReader bf; static PrintWriter pw; static int n; static long mod=998244353l; static int MAXN=61; static long[][] comb = new long[MAXN][MAXN]; static long dp[][]; static void pre(){ comb[0][0] = 1; for (int i = 1; i < MAXN; i++) { comb[i][0] = 1; for (int j = 1; j <= i; j++) { comb[i][j] = (comb[i-1][j] + comb[i-1][j-1]) % mod; } } } static void solve(int idx) throws Exception{ if(idx==2) return; solve(idx-2); dp[idx][0]=(comb[idx-1][idx/2-1]+dp[idx-2][1])%mod; dp[idx][1]=(comb[idx-2][idx/2-2]+dp[idx-2][0])%mod; dp[idx][2]=dp[idx-2][2]%mod; } public static void main(String[] args) throws java.lang.Exception { boolean lenv=false; int te=1; 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)); } pre(); int q1 = Integer.parseInt(bf.readLine().trim()); for(te=1;te<=q1;te++) { n=Integer.parseInt(bf.readLine().trim()); dp=new long[n+1][3]; for(int i=0;i<=n;i++) for(int j=0;j<3;j++) dp[i][j]=-1; dp[2][0]=1; dp[2][1]=0; dp[2][2]=1; solve(n); str.append(dp[n][0]).append(" ").append(dp[n][1]).append(" ").append(dp[n][2]).append("\n"); } pw.print(str); pw.flush(); // System.out.println(str); } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
39646f6c96cd7f10a2a113727227d6ad
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.util.*; public class C_Card_Game { static int MOD = 998244353; public static int solve(int n){ if(n <= 0) return 0; // total games nCn/2 // number of games Alex wins -> if he receives number n then alex wins int a1 = modncr(n-1,(n/2)-1); int a2 = modncr(n-4, (n/2 -3)); int a3 = solve(n-4); // System.out.println(n+"="+a1+","+a2+","+a3); return add(add(a1,a2),a3); } public static int add (int a, int b){ return (a+b)%MOD; } // 6 /** n=12 A -> [12,x,x,x,x,x] -> 11C5 -> 462 A -> [x,x,x,9,10,11] -> 8C3 -> 56 n=6 1 2 3 4 5 6 A -> [6,x,x] (5C2 == 10) A -> [3,4,5] & B -> [1,2,6] (n/2C(n/2 -1)) A -> [2,4,5] & B -> [1,3,6] A -> [x,x,6,7] & B -> [x,x,x,8] 4 5 6 7 1 2 3 8 -> 3 op1 : 1 2 3 4 - - - - [x,5,6,7] , [x,x,x,8] -> 4 op2 : 1 2 3 - - - - - [x,4,6,7] , [x,x,5,8] -> 3 -> [x,4], [x,x] -> size reduced by 2 n = 8 A -> [x,x,x,8] -> 7C3 = 35 A -> [x,x] -> 3C2 -> 3 A -> [x,-,-,-] -> (n-4)C(n/2 -3) -> 4 */ public static int modncr(int n, int r){ if(n <= 0) return 0; long num = 1, den = 1; while(r >= 1){ num = (num * n) % MOD; den = (den * r) % MOD; n--;r--; } long cur =( num * modinv(den)) % MOD; return (int)cur; } public static long modinv(long a){ return power(a, MOD-2, MOD); } public 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; } public static void main(String[] args) throws Exception{ int T = in.readInt(); while(T-->0){ int N = in.readInt(); // nCn/2 // System.out.println(modncr(8,3)); int a = solve(N); int t = modncr(N,N/2); int d = 1; int b = (t - a -d + MOD)%MOD; System.out.println(a+" "+b+" "+d); } } // snippets // readint, readlong -> ri, rl // readA, readLA -> ria, rla // readline -> r // System.out.println() -> sop static Inputer in; static { in = new Inputer(); } static class Inputer{ BufferedReader br; Inputer(){ try{ br = new BufferedReader(new InputStreamReader(System.in)); } catch(Exception e){} } public int readInt() throws Exception{ return Integer.parseInt(readLine()); } public long readLong() throws Exception{ return Long.parseLong(readLine()); } public int[] readA(String delim) throws Exception{ String[] s = readLine().split(delim); int[] A = new int[s.length]; for(int i = 0; i < s.length; i++) A[i] = Integer.parseInt(s[i]); return A; } public int[] readA() throws Exception{ String[] s = readLine().split("\\s+"); int[] A = new int[s.length]; for(int i = 0; i < s.length; i++) A[i] = Integer.parseInt(s[i]); return A; } public long[] readLA() throws Exception{ String[] s = readLine().split("\\s+"); long[] A = new long[s.length]; for(int i = 0; i < s.length; i++) A[i] = Long.parseLong(s[i]); return A; } public String readLine() throws Exception{ return br.readLine(); } public int[] copyA(int[] A){ int[] B = new int[A.length]; for(int i= 0 ; i < A.length; i++) B[i] = A[i]; return B; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
794d2bead795d2a2308810fc41c8d4b8
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; public class C { static final long modL = (long) 1e9 + 7l; static final long mod = 998244353; static long dp[][] = new long[35][2]; private static void solve(int tt){ int n = fs.nextInt(); out.println(dp[n/2][0]+" "+dp[n/2][1]+" "+1); } private static void preprocess() { int k; dp[1] = new long[]{1,0}; //2 dp[2] = new long[]{3,2}; //4 dp[3] = new long[]{12,7}; //6 dp[4] = new long[]{42,27}; //8 for (int i = 5; i < 31; i++) { int card = i*2; dp[i][0] = (nCk(card-1, i-1) + dp[i-1][1])%mod; dp[i][1] = (nCk(card, i) - dp[i][0] + mod)%mod; dp[i][1]--; } } private static int[] sortByCollections(int[] arr) { ArrayList<Integer> ls = new ArrayList<>(arr.length); for (int i = 0; i < arr.length; i++) { ls.add(arr[i]); } Collections.sort(ls); for (int i = 0; i < arr.length; i++) { arr[i] = ls.get(i); } return arr; } public static void main(String[] args) { preprocess(); fs = new FastScanner(); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); int t = fs.nextInt(); for (int i = 1; i <= t; i++) solve(t); out.close(); // System.err.println( System.currentTimeMillis() - s + "ms" ); } static boolean DEBUG = true; static PrintWriter out; static FastScanner fs; static void trace(Object... o) { if (!DEBUG) return; System.err.println(Arrays.deepToString(o)); } static void pl(Object o) { out.println(o); } static void p(Object o) { out.print(o); } static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } static void sieveOfEratosthenes(int n, int factors[]) { factors[1] = 1; for (int p = 2; p * p <= n; p++) { if (factors[p] == 0) { factors[p] = p; for (int i = p * p; i <= n; i += p) factors[i] = p; } } } static long mul(long a, long b) { return a * b % mod; } static long fact(int x) { long ans = 1; for (int i = 2; i <= x; i++) ans = mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp == 0) return 1; long half = fastPow(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static long modInv(long x) { return fastPow(x, mod - 2); } static long nCk(int n, int k) { return mul(fact(n), mul(modInv(fact(k)), modInv(fact(n - k)))); } 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(); } 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()); } } static class _Scanner { InputStream is; _Scanner(InputStream is) { this.is = is; } byte[] bb = new byte[1 << 15]; int k, l; byte getc() throws IOException { if (k >= l) { k = 0; l = is.read(bb); if (l < 0) return -1; } return bb[k++]; } byte skip() throws IOException { byte b; while ((b = getc()) <= 32) ; return b; } int nextInt() throws IOException { int n = 0; for (byte b = skip(); b > 32; b = getc()) n = n * 10 + b - '0'; return n; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
ba37f1fa78cec8ea6bcf7d72ae23f000
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; public class Main { 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()); long[][] dp = new long[n / 2 + 1][2]; dp[1][0] = 1; dp[1][1] = 0; for (int i = 2; i <= n / 2; i++) { dp[i][0] = c(i * 2 - 1, i - 1) + dp[i - 1][1]; dp[i][1] = c(i * 2, i) - dp[i][0] - 1; } System.out.println(dp[n / 2][0] % 998244353 + " " + dp[n / 2][1] % 998244353 + " 1"); } } public static long c(int n, int k) { BigDecimal d = BigDecimal.ONE; for (int i = k + 1; i <= n; i++) { d = d.multiply(BigDecimal.valueOf(i)); } for (int i = 2; i <= n - k; i++) { d = d.divide(BigDecimal.valueOf(i)); } return d.longValue(); } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
69ab6525fa43bb939c4084edfb8c04d7
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author tauros */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; RealFastReader in = new RealFastReader(inputStream); FastWriter out = new FastWriter(outputStream); CF1739C solver = new CF1739C(); solver.solve(1, in, out); out.close(); } static class CF1739C { public void solve(int testNumber, RealFastReader in, FastWriter out) { final int MOD = 998244353; int cases = in.ni(); while (cases-- > 0) { int n = in.ni(); int a = 0, b = 0; Comb comb = new Comb(n, MOD); for (int i = n, cur = 0; i > 0; i -= 2, cur ^= 1) { if (cur == 0) { a += comb.c(i - 1, i / 2 - 1); if (a >= MOD) { a -= MOD; } b += comb.c(i - 2, i / 2 - 2); if (b >= MOD) { b -= MOD; } } else { b += comb.c(i - 1, i / 2 - 1); if (b >= MOD) { b -= MOD; } a += comb.c(i - 2, i / 2 - 2); if (a >= MOD) { a -= MOD; } } } int total = comb.c(n, n / 2); int d = ((total - a - b) % MOD + MOD) % MOD; out.println(a + " " + b + " " + d); } out.flush(); } } static class Comb { private final int mod; private final int maxn; public final int[] fac; public final int[] inv; public final int[] facInv; public Comb(final int maxn, final int mod) { this.maxn = maxn; this.mod = mod; this.fac = new int[maxn + 1]; this.inv = new int[maxn + 1]; this.facInv = new int[maxn + 1]; fac[0] = 1; facInv[0] = 1; for (int i = 1; i <= maxn; i++) { inv[i] = i == 1 ? 1 : Common.inv(i, mod, inv[mod % i]); fac[i] = (int) ((long) fac[i - 1] * i % mod); facInv[i] = (int) ((long) facInv[i - 1] * inv[i] % mod); } } public int c(int n, int m) { if (n > maxn || m > n || n < 0 || m < 0) { return 0; } return (int) ((long) fac[n] * facInv[m] % mod * facInv[n - m] % mod); } } static class FastWriter { private final PrintWriter writer; public FastWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream), 8192)); } public FastWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(String x) { writer.println(x); } public void flush() { writer.flush(); } public void close() { writer.flush(); try { writer.close(); } catch (Exception e) { e.printStackTrace(); } } } static class RealFastReader { InputStream is; private byte[] inbuf = new byte[8192]; public int lenbuf = 0; public int ptrbuf = 0; public RealFastReader(final InputStream is) { this.is = is; } public int readByte() { if (lenbuf == -1) { throw new InputMismatchException(); } if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) { return -1; } } return inbuf[ptrbuf++]; } public int ni() { int num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } static final class Common { public static int inv(int a, int p, int invPModA) { return (int) inv((long) a, p, invPModA); } public static long inv(long a, long p, long invPModA) { long ans = -p / a * invPModA % p; if (ans < 0) { ans += p; } return ans; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
837eea40e5a7e3287bbf6129d053f074
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author tauros */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; RealFastReader in = new RealFastReader(inputStream); FastWriter out = new FastWriter(outputStream); CF1739C solver = new CF1739C(); solver.solve(1, in, out); out.close(); } static class CF1739C { public void solve(int testNumber, RealFastReader in, FastWriter out) { final int MOD = 998244353; int cases = in.ni(); while (cases-- > 0) { int n = in.ni(); int a = 0, b = 0, d = 1; Comb comb = new Comb(n, MOD); for (int i = n, cur = 0; i > 0; i -= 2, cur ^= 1) { if (cur == 0) { a += comb.c(i - 1, i / 2 - 1); if (a >= MOD) { a -= MOD; } b += comb.c(i - 2, i / 2 - 2); if (b >= MOD) { b -= MOD; } } else { b += comb.c(i - 1, i / 2 - 1); if (b >= MOD) { b -= MOD; } a += comb.c(i - 2, i / 2 - 2); if (a >= MOD) { a -= MOD; } } } out.println(a + " " + b + " " + d); } out.flush(); } } static class Comb { private final int mod; private final int maxn; public final int[] fac; public final int[] inv; public final int[] facInv; public Comb(final int maxn, final int mod) { this.maxn = maxn; this.mod = mod; this.fac = new int[maxn + 1]; this.inv = new int[maxn + 1]; this.facInv = new int[maxn + 1]; fac[0] = 1; facInv[0] = 1; for (int i = 1; i <= maxn; i++) { inv[i] = i == 1 ? 1 : Common.inv(i, mod, inv[mod % i]); fac[i] = (int) ((long) fac[i - 1] * i % mod); facInv[i] = (int) ((long) facInv[i - 1] * inv[i] % mod); } } public int c(int n, int m) { if (n > maxn || m > n || n < 0 || m < 0) { return 0; } return (int) ((long) fac[n] * facInv[m] % mod * facInv[n - m] % mod); } } static class FastWriter { private final PrintWriter writer; public FastWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream), 8192)); } public FastWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(String x) { writer.println(x); } public void flush() { writer.flush(); } public void close() { writer.flush(); try { writer.close(); } catch (Exception e) { e.printStackTrace(); } } } static class RealFastReader { InputStream is; private byte[] inbuf = new byte[8192]; public int lenbuf = 0; public int ptrbuf = 0; public RealFastReader(final InputStream is) { this.is = is; } public int readByte() { if (lenbuf == -1) { throw new InputMismatchException(); } if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) { return -1; } } return inbuf[ptrbuf++]; } public int ni() { int num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } static final class Common { public static int inv(int a, int p, int invPModA) { return (int) inv((long) a, p, invPModA); } public static long inv(long a, long p, long invPModA) { long ans = -p / a * invPModA % p; if (ans < 0) { ans += p; } return ans; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
23e8c4e56315af8d806525aaf89e9bca
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; public class Main { static InputReader in; static OutputWriter out; static long[][] c=new long[65][65]; static long mod=998244353; public static void main(String[] args) throws Exception { in=new InputReader(System.in); out=new OutputWriter(System.out); for(int i=0;i<=60;i++) { c[i][0]=1; for(int j=1;j<=i;j++) c[i][j]=(c[i-1][j-1]+c[i-1][j])%mod; } int T=in.nextInt(); while(T-->0) { int n=in.nextInt(); long ans1=0; long ans2=0; for(int i=0;i<n/2;i++) { if(i%2==0) ans1=(ans1+C(n-2*i-1,n/2-i-1))%mod; else ans1=(ans1+C(n-2*i-2,n/2-i-2))%mod; } for(int i=0;i<n/2;i++) { if(i%2!=0) ans2=(ans2+C(n-2*i-1,n/2-i-1))%mod; else ans2=(ans2+C(n-2*i-2,n/2-i-2))%mod; } out.println(ans1+" "+ans2+" "+1); } out.flush(); } private static long C(int a,int b) { if(b>a) return 0; if(a<=0 || b<0) return 0; return c[a][b]; } static class InputReader { private final BufferedReader br; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public int nextInt() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } boolean negative = false; if (c == '-') { negative = true; c = br.read(); } int x = 0; while (c > 32) { x = x * 10 + c - '0'; c = br.read(); } return negative ? -x : x; } public long nextLong() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } boolean negative = false; if (c == '-') { negative = true; c = br.read(); } long x = 0; while (c > 32) { x = x * 10 + c - '0'; c = br.read(); } return negative ? -x : x; } public String next() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } StringBuilder sb = new StringBuilder(); while (c > 32) { sb.append((char) c); c = br.read(); } return sb.toString(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } static class OutputWriter { private final BufferedWriter writer; public OutputWriter(OutputStream out) { writer=new BufferedWriter(new OutputStreamWriter(out)); } public void print(String str) { try { writer.write(str); } catch (IOException e) { e.printStackTrace(); } } public void print(Object obj) { print(String.valueOf(obj)); } public void println(String str) { print(str+"\n"); } public void println() { print('\n'); } public void println(Object obj) { println(String.valueOf(obj)); } public void flush() { try { writer.flush(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
be65e503cd160167d1de74337353ad8e
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
/*############################################################################################################ ########################################## >>>> Diaa12360 <<<< ############################################### ########################################### Just Nothing ################################################# #################################### If You Need it, Fight For IT; ######################################### ###############################################.-. 1 5 9 2 .-.################################################ ############################################################################################################*/ import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Solution { public static void main(String[] args) throws Exception { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); int[][] ans = {{1, 0}, {3, 2}, {12, 7}, {42, 27}, {153, 98}, {560, 363}, {2079, 1352}, {7787, 5082}, {29392, 19227}, {111605, 73150}, {425866, 279565}, {1631643, 1072512}, {6272812, 4127787}, {24186087, 15930512}, {93489272, 61628247}, {362168442, 238911947}, {407470704, 927891162}, {474237047, 614943428}, {319176974, 87534470}, {131938523, 955113935}, {558075845, 644336680}, {544270478, 253841470}, {209493498, 700054910}, {859106804, 457241336}, {921005664, 6522991}, {366933608, 353887625}, {142064435, 432533537}, {741221694, 874398972}, {297907370, 545598131}, {341102826, 248150916}}; while (t-- > 0) { int n = in.nextInt() / 2 - 1; out.print(ans[n][0] % 998244353); out.print(' '); out.print(ans[n][1] % 998244353); out.print(' '); out.println(1); } out.flush(); } static int lcm(int a, int b) { return a / gcd(a, b) * b; } static int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b % a, a); } //all primes static ArrayList<Integer> primes; static boolean[] primesB; //sieve algorithm static void sieve(int n) { primes = new ArrayList<>(); primesB = new boolean[n + 1]; for (int i = 2; i <= n; i++) { primesB[i] = true; } for (int i = 2; i * i <= n; i++) { if (primesB[i]) { for (int j = i * i; j <= n; j += i) { primesB[j] = false; } } } for (int i = 0; i <= n; i++) { if (primesB[i]) { primes.add(i); } } } // Function to find gcd of array of // numbers static int findGCD(int[] arr, int n) { int result = arr[0]; for (int element : arr) { result = gcd(result, element); if (result == 1) { return 1; } } return result; } private static class FastScanner { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private FastScanner() throws IOException { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private short nextShort() throws IOException { short ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = (short) (ret * 10 + c - '0'); while ((c = read()) >= '0' && c <= '9'); if (neg) return (short) -ret; return ret; } private 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; } private char nextChar() throws IOException { byte c = read(); while (c <= ' ') c = read(); return (char) c; } private String nextString() throws IOException { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); } while ((c = read()) > ' '); return ret.toString(); } 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++]; } } private static int anInt(String s) { return Integer.parseInt(s); } private static long ll(String s) { return Long.parseLong(s); } } class Pair<K, V> implements Comparable<Pair<K, V>> { K first; V second; Pair(K f, V s) { first = f; second = s; } @Override public int compareTo(Pair<K, V> o) { return 0; } } class PairInt implements Comparable<PairInt> { int first; int second; PairInt(int f, int s) { first = f; second = s; } @Override public int compareTo(PairInt o) { if (this.first > o.first) { return 1; } else if (this.first < o.first) return -1; else { if (this.second < o.second) return 1; else if (this.second == o.second) return -1; return 0; } } @Override public String toString() { return "<" + first + ", " + second + ">"; } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
4e9b421b5b4ea7e315efd2b7952802a8
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
/*############################################################################################################ ########################################## >>>> Diaa12360 <<<< ############################################### ########################################### Just Nothing ################################################# #################################### If You Need it, Fight For IT; ######################################### ###############################################.-. 1 5 9 2 .-.################################################ ############################################################################################################*/ import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Solution { public static void main(String[] args) throws Exception { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); int[][] ans = {{1, 0}, {3, 2}, {12, 7}, {42, 27}, {153, 98}, {560, 363}, {2079, 1352}, {7787, 5082}, {29392, 19227}, {111605, 73150}, {425866, 279565}, {1631643, 1072512}, {6272812, 4127787}, {24186087, 15930512}, {93489272, 61628247}, {362168442, 238911947}, {407470704, 927891162}, {474237047, 614943428}, {319176974, 87534470}, {131938523, 955113935}, {558075845, 644336680}, {544270478, 253841470}, {209493498, 700054910}, {859106804, 457241336}, {921005664, 6522991}, {366933608, 353887625}, {142064435, 432533537}, {741221694, 874398972}, {297907370, 545598131}, {341102826, 248150916}}; while (t-- > 0) { int n = in.nextInt() / 2 - 1; out.print(ans[n][0]); out.print(' '); out.print(ans[n][1]); out.print(' '); out.println(1); } out.flush(); } static int lcm(int a, int b) { return a / gcd(a, b) * b; } static int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b % a, a); } //all primes static ArrayList<Integer> primes; static boolean[] primesB; //sieve algorithm static void sieve(int n) { primes = new ArrayList<>(); primesB = new boolean[n + 1]; for (int i = 2; i <= n; i++) { primesB[i] = true; } for (int i = 2; i * i <= n; i++) { if (primesB[i]) { for (int j = i * i; j <= n; j += i) { primesB[j] = false; } } } for (int i = 0; i <= n; i++) { if (primesB[i]) { primes.add(i); } } } // Function to find gcd of array of // numbers static int findGCD(int[] arr, int n) { int result = arr[0]; for (int element : arr) { result = gcd(result, element); if (result == 1) { return 1; } } return result; } private static class FastScanner { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private FastScanner() throws IOException { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private short nextShort() throws IOException { short ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = (short) (ret * 10 + c - '0'); while ((c = read()) >= '0' && c <= '9'); if (neg) return (short) -ret; return ret; } private 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; } private char nextChar() throws IOException { byte c = read(); while (c <= ' ') c = read(); return (char) c; } private String nextString() throws IOException { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); } while ((c = read()) > ' '); return ret.toString(); } 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++]; } } private static int anInt(String s) { return Integer.parseInt(s); } private static long ll(String s) { return Long.parseLong(s); } } class Pair<K, V> implements Comparable<Pair<K, V>> { K first; V second; Pair(K f, V s) { first = f; second = s; } @Override public int compareTo(Pair<K, V> o) { return 0; } } class PairInt implements Comparable<PairInt> { int first; int second; PairInt(int f, int s) { first = f; second = s; } @Override public int compareTo(PairInt o) { if (this.first > o.first) { return 1; } else if (this.first < o.first) return -1; else { if (this.second < o.second) return 1; else if (this.second == o.second) return -1; return 0; } } @Override public String toString() { return "<" + first + ", " + second + ">"; } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
8ce1c08f2c16e2121e9467f4c76f1912
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.util.*; import java.io.*; public class Main { static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); static int dx[]={0,0,-1,1,-1,-1,1,1},dy[]={-1,1,0,0,-1,1,-1,1}; static final double pi=3.1415926536; // static long mod=1000000007; static long mod=998244353; static int MAX=Integer.MAX_VALUE; static int MIN=Integer.MIN_VALUE; static long MAXL=Long.MAX_VALUE; static long MINL=Long.MIN_VALUE; static ArrayList<Integer> graph[]; static long fact[]; static long seg[]; static long dp[][]; // static long dp[][]; public static void main (String[] args) throws java.lang.Exception { // code goes here fact=new long[100]; fact[0]=1L; for(long i=1;i<100;i++){ fact[(int)i]=mul(fact[(int)(i-1)],i); } long a[]=new long[65]; long b[]=new long[65]; a[2]=1; b[2]=0; for(int i=4;i<65;i+=2){ a[i]=add(nCr(i-1,(i/2)-1),b[i-2]); long total=nCr(i,i/2); total=sub(total,1); b[i]=sub(total,a[i]); } int t=I(); outer:while(t-->0) { int n=I(); out.println(a[n]+" "+b[n]+" 1"); } out.close(); } public static class pair { int a; int b; public pair(int aa,int bb) { a=aa; b=bb; } } public static class myComp implements Comparator<pair> { //sort in ascending order. public int compare(pair p1,pair p2) { if(p1.a==p2.a) return p1.b-p2.b; else if(p1.a<p2.a) return -1; else return 1; } // sort in descending order. // public int compare(pair p1,pair p2) // { // if(p1.b==p2.b) // return 0; // else if(p1.b<p2.b) // return 1; // else // return -1; // } } public static void setGraph(int n,int m)throws IOException { graph=new ArrayList[n+1]; for(int i=0;i<=n;i++){ graph[i]=new ArrayList<>(); } for(int i=0;i<m;i++){ int u=I(),v=I(); graph[u].add(v); graph[v].add(u); } } //LOWER_BOUND and UPPER_BOUND functions //It returns answer according to zero based indexing. public static int lower_bound(pair[] arr,int X,int start, int end) //start=0,end=n-1 { if(start>end)return -1; // if(arr.get(end)<X)return end; if(arr[end].a<X)return end; // if(arr.get(start)>X)return -1; if(arr[start].a>X)return -1; int left=start,right=end; while(left<right){ int mid=(left+right)/2; if(arr[mid].a==X){ // if(arr.get(mid)==X){ //Returns last index of lower bound value. if(mid<end && arr[mid+1].a==X){ // if(mid<end && arr.get(mid+1)==X){ left=mid+1; }else{ return mid; } } // if(arr.get(mid)==X){ //Returns first index of lower bound value. // if(arr[mid]==X){ // // if(mid>start && arr.get(mid-1)==X){ // if(mid>start && arr[mid-1]==X){ // right=mid-1; // }else{ // return mid; // } // } else if(arr[mid].a>X){ // else if(arr.get(mid)>X){ if(mid>start && arr[mid-1].a<X){ // if(mid>start && arr.get(mid-1)<X){ return mid-1; }else{ right=mid-1; } }else{ if(mid<end && arr[mid+1].a>X){ // if(mid<end && arr.get(mid+1)>X){ return mid; }else{ left=mid+1; } } } return left; } //It returns answer according to zero based indexing. public static int upper_bound(long arr[],long X,int start,int end) //start=0,end=n-1 { if(arr[0]>=X)return start; if(arr[arr.length-1]<X)return -1; int left=start,right=end; while(left<right){ int mid=(left+right)/2; if(arr[mid]==X){ //returns first index of upper bound value. if(mid>start && arr[mid-1]==X){ right=mid-1; }else{ return mid; } } // if(arr[mid]==X){ //returns last index of upper bound value. // if(mid<end && arr[mid+1]==X){ // left=mid+1; // }else{ // return mid; // } // } else if(arr[mid]>X){ if(mid>start && arr[mid-1]<X){ return mid; }else{ right=mid-1; } }else{ if(mid<end && arr[mid+1]>X){ return mid+1; }else{ left=mid+1; } } } return left; } //END //Segment Tree Code public static void buildTree(long a[],int si,int ss,int se) { if(ss==se){ seg[si]=a[ss]; return; } int mid=(ss+se)/2; buildTree(a,2*si+1,ss,mid); buildTree(a,2*si+2,mid+1,se); seg[si]=max(seg[2*si+1],seg[2*si+2]); } // public static void update(int si,int ss,int se,int pos,int val) // { // if(ss==se){ // // seg[si]=val; // return; // } // int mid=(ss+se)/2; // if(pos<=mid){ // update(2*si+1,ss,mid,pos,val); // }else{ // update(2*si+2,mid+1,se,pos,val); // } // // seg[si]=min(seg[2*si+1],seg[2*si+2]); // if(seg[2*si+1].a < seg[2*si+2].a){ // seg[si].a=seg[2*si+1].a; // seg[si].b=seg[2*si+1].b; // }else{ // seg[si].a=seg[2*si+2].a; // seg[si].b=seg[2*si+2].b; // } // } public static long query(int si,int ss,int se,int qs,int qe) { if(qs>se || qe<ss)return 0; if(ss>=qs && se<=qe)return seg[si]; int mid=(ss+se)/2; long p1=query(2*si+1,ss,mid,qs,qe); long p2=query(2*si+2,mid+1,se,qs,qe); return max(p1,p2); } public static void merge(ArrayList<Integer> f,ArrayList<Integer> a,ArrayList<Integer> b) { int i=0,j=0; while(i<a.size() && j<b.size()){ if(a.get(i)<=b.get(j)){ f.add(a.get(i)); i++; }else{ f.add(b.get(j)); j++; } } while(i<a.size()){ f.add(a.get(i)); i++; } while(j<b.size()){ f.add(b.get(j)); j++; } } //Segment Tree Code end //Prefix Function of KMP Algorithm public static int[] KMP(char c[],int n) { int pi[]=new int[n]; for(int i=1;i<n;i++){ int j=pi[i-1]; while(j>0 && c[i]!=c[j]){ j=pi[j-1]; } if(c[i]==c[j])j++; pi[i]=j; } return pi; } public static long kadane(long a[],int n) //largest sum subarray { long max_sum=Long.MIN_VALUE,max_end=0; for(int i=0;i<n;i++){ max_end+=a[i]; if(max_sum<max_end){max_sum=max_end;} if(max_end<0){max_end=0;} } return max_sum; } public static ArrayList<Long> primeFact(long x) { ArrayList<Long> arr=new ArrayList<>(); if(x%2==0){ arr.add(2L); while(x%2==0){ x/=2; } } for(long i=3;i*i<=x;i+=2){ if(x%i==0){ arr.add(i); while(x%i==0){ x/=i; } } } if(x>0){ arr.add(x); } return arr; } public static long nPr(int n,int r) { long ans=divide(fact(n),fact(n-r),mod); return ans; } public static long nCr(int n,int r) { long ans=divide(fact[n],mul(fact[n-r],fact[r]),mod); return ans; } public static boolean isSorted(int a[]) { int n=a.length; for(int i=0;i<n-1;i++){ if(a[i]>a[i+1])return false; } return true; } public static boolean isSorted(long a[]) { int n=a.length; for(int i=0;i<n-1;i++){ if(a[i]>a[i+1])return false; } return true; } public static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } public static int computeXOR(int n) //compute XOR of all numbers between 1 to n. { if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; return 0; } public static int np2(int x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; } public static int hp2(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } public static long hp2(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } public static ArrayList<Integer> primeSieve(int n) { ArrayList<Integer> arr=new ArrayList<>(); boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int i = 2; i <= n; i++) { if (prime[i] == true) arr.add(i); } return arr; } // Fenwick / BinaryIndexed Tree USE IT - FenwickTree ft1=new FenwickTree(n); public static class FenwickTree { int farr[]; int n; public FenwickTree(int c) { n=c+1; farr=new int[n]; } // public void update_range(int l,int r,long p) // { // update(l,p); // update(r+1,(-1)*p); // } public void update(int x,int p) { for(;x<n;x+=x&(-x)) { farr[x]+=p; } } public int get(int x) { int ans=0; for(;x>0;x-=x&(-x)) { ans=ans+farr[x]; } return ans; } } //Disjoint Set Union //NOTE: call find function for all the index in the par array at last, //in order to set parent of every index properly. public static class DSU { int par[],rank[]; public DSU(int c) { par=new int[c+1]; rank=new int[c+1]; for(int i=0;i<=c;i++) { par[i]=i; rank[i]=0; } } public int find(int a) { if(a==par[a]) return a; return par[a]=find(par[a]); } public void union(int a,int b) { int a_rep=find(a),b_rep=find(b); if(a_rep==b_rep) return; if(rank[a_rep]<rank[b_rep]) par[a_rep]=b_rep; else if(rank[a_rep]>rank[b_rep]) par[b_rep]=a_rep; else { par[b_rep]=a_rep; rank[a_rep]++; } } } public static boolean isVowel(char c) { if(c=='a' || c=='e' || c=='i' || c=='u' || c=='o')return true; return false; } public static boolean isInteger(double N) { int X = (int)N; double temp2 = N - X; if (temp2 > 0) { return false; } return true; } public static boolean isPalindrome(String s) { int n=s.length(); for(int i=0;i<=n/2;i++){ if(s.charAt(i)!=s.charAt(n-i-1)){ return false; } } return true; } public static int gcd(int a,int b) { if(b==0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } public static long fact(long n) { long fact=1; for(long i=2;i<=n;i++){ fact=((fact%mod)*(i%mod))%mod; } return fact; } public static long fact(int n) { long fact=1; for(int i=2;i<=n;i++){ fact=((fact%mod)*(i%mod))%mod; } return fact; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static void printArray(long a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(int a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(char a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]); } out.println(); } public static void printArray(String a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(boolean a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(pair a[]) { for(pair p:a){ out.println(p.a+"->"+p.b); } } public static void printArray(int a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(String a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(boolean a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(long a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(char a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(ArrayList<?> arr) { for(int i=0;i<arr.size();i++){ out.print(arr.get(i)+" "); } out.println(); } public static void printMapI(HashMap<?,?> hm){ for(Map.Entry<?,?> e:hm.entrySet()){ out.println(e.getKey()+"->"+e.getValue()); }out.println(); } public static void printMap(HashMap<Long,ArrayList<Integer>> hm){ for(Map.Entry<Long,ArrayList<Integer>> e:hm.entrySet()){ out.print(e.getKey()+"->"); ArrayList<Integer> arr=e.getValue(); for(int i=0;i<arr.size();i++){ out.print(arr.get(i)+" "); }out.println(); } } public static void printGraph(ArrayList<Integer> graph[]) { int n=graph.length; for(int i=0;i<n;i++){ out.print(i+"->"); for(int j:graph[i]){ out.print(j+" "); }out.println(); } } //Modular Arithmetic public static long add(long a,long b) { a+=b; if(a>=mod)a-=mod; return a; } public static long sub(long a,long b) { a-=b; if(a<0)a+=mod; return a; } public static long mul(long a,long b) { return ((a%mod)*(b%mod))%mod; } public static long divide(long a,long b,long m) { a=mul(a,modInverse(b,m)); return a; } public static long modInverse(long a,long m) { int x=0,y=0; own p=new own(x,y); long g=gcdExt(a,m,p); if(g!=1){ out.println("inverse does not exists"); return -1; }else{ long res=((p.a%m)+m)%m; return res; } } public static long gcdExt(long a,long b,own p) { if(b==0){ p.a=1; p.b=0; return a; } int x1=0,y1=0; own p1=new own(x1,y1); long gcd=gcdExt(b,a%b,p1); p.b=p1.a - (a/b) * p1.b; p.a=p1.b; return gcd; } public static long pwr(long m,long n) { long res=1; if(m==0) return 0; while(n>0) { if((n&1)!=0) { res=(res*m); } n=n>>1; m=(m*m); } return res; } public static long modpwr(long m,long n) { long res=1; m=m%mod; if(m==0) return 0; while(n>0) { if((n&1)!=0) { res=(res*m)%mod; } n=n>>1; m=(m*m)%mod; } return res; } public static class own { long a; long b; public own(long val,long index) { a=val; b=index; } } //Modular Airthmetic public static void sort(int[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public static void sort(char[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { char tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public static void sort(long[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } //max & min public static int max(int a,int b){return Math.max(a,b);} public static int min(int a,int b){return Math.min(a,b);} public static int max(int a,int b,int c){return Math.max(a,Math.max(b,c));} public static int min(int a,int b,int c){return Math.min(a,Math.min(b,c));} public static long max(long a,long b){return Math.max(a,b);} public static long min(long a,long b){return Math.min(a,b);} public static long max(long a,long b,long c){return Math.max(a,Math.max(b,c));} public static long min(long a,long b,long c){return Math.min(a,Math.min(b,c));} public static int maxinA(int a[]){int n=a.length;int mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;} public static long maxinA(long a[]){int n=a.length;long mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;} public static int mininA(int a[]){int n=a.length;int mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;} public static long mininA(long a[]){int n=a.length;long mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;} public static long suminA(int a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;} public static long suminA(long a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;} //end public static int[] I(int n)throws IOException{int a[]=new int[n];for(int i=0;i<n;i++){a[i]=I();}return a;} public static long[] IL(int n)throws IOException{long a[]=new long[n];for(int i=0;i<n;i++){a[i]=L();}return a;} public static long[] prefix(int a[]){int n=a.length;long pre[]=new long[n];pre[0]=a[0];for(int i=1;i<n;i++){pre[i]=pre[i-1]+a[i];}return pre;} public static long[] prefix(long a[]){int n=a.length;long pre[]=new long[n];pre[0]=a[0];for(int i=1;i<n;i++){pre[i]=pre[i-1]+a[i];}return pre;} public static int I()throws IOException{return sc.I();} public static long L()throws IOException{return sc.L();} public static String S()throws IOException{return sc.S();} public static double D()throws IOException{return sc.D();} } class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()){ try { st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int I(){ return Integer.parseInt(next());} long L(){ return Long.parseLong(next());} double D(){return Double.parseDouble(next());} String S(){ String str = ""; try { str = br.readLine(); } catch (IOException e){ e.printStackTrace(); } return str; } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
73317488a0c8d7ce1162967c18dc97d1
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
// OM NAMAH SHIVAY // 32 days remaining(2609) import java.math.BigInteger; import java.util.*; import java.io.*; public class Vaibhav { static long bit[]; static boolean prime[]; static class Pair { int a; int b; Pair(int a, int b ) { this.a = a; this.b = b; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair) o; return p.a == a && p.b == b; } return false; } public int hashCode() { int hash = 5; hash = 17 * hash + this.a; return hash; } } static long power(long x, long y, long p) { if (y == 0) return 1; if (x == 0) return 0; long res = 1l; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long power(long x, long y) { if (y == 0) return 1; if (x == 0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readlongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } static void sieveOfEratosthenes(int n) { prime = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } } public static int log2(int x) { return (int) (Math.log(x) / Math.log(2)); } static long binomialCoeff(long n, long r) { if (r > n) return 0l; long m = 998244353l; long inv[] = new long[(int)r + 1]; inv[0] = 1; if(r+1>=2) inv[1] = 1; for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[(int) (m % i)] % m; } long ans = 1l; for (int i = 2; i <= r; i++) { ans = (int) (((ans % m) * (inv[i] % m)) % m); } for (int i = (int)n; i >= (n - r + 1); i--) { ans = (int) (((ans % m) * (i % m)) % m); } return ans; } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } static BigInteger bi(String str) { return new BigInteger(str); } // Author - vaibhav_1710 static FastScanner fs = null; static int mod= 1_000_000_00; static int a[]; static int p[]; static int[][] dirs = { { 0, -1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, }; static int dp[][][]; static ArrayList<Integer> al[]; static int k1; static int k2; static long m = 998244353l; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t=fs.nextInt(); long dp[] = new long[61]; dp[2]=1l; dp[4]=3l; for(int i=6;i<=60;i+=2){ long cal1 = binomialCoeff(i-2,(i-2)/2); dp[i] = (cal1 - dp[i-2]-1+m)%m; int v = i/2; v--; long cal = binomialCoeff(i-1,v); dp[i] = (dp[i] + cal)%m; } outer:while(t-->0) { int n = fs.nextInt(); long ans = binomialCoeff(n,n/2); long aw = dp[n]; long bw = (ans-dp[n]-1+m)%m; out.println(aw+" "+bw+" "+1); } out.close(); } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
442851151579bb6ef38b1b588e912979
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
//package kg.my_algorithms.Codeforces; import java.util.*; import java.io.*; // NO PROFILE CHECK public class Solution { private static final FastReader fr = new FastReader(); private static final long mod = 998244353L; public static void main(String[] args) throws IOException { BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); int ts = fr.nextInt(); Combinatorics comb = new Combinatorics(61); long[] alice = new long[61]; long[] bob = new long[61]; alice[2] = 1L; for(int i=4;i<=60;i+=2){ alice[i] = (comb.C(i-1,i/2-1)+bob[i-2])%mod; bob[i] = (comb.C(i-2,i/2-2)+alice[i-2])%mod; } for(int t=0;t<ts;t++){ int n = fr.nextInt(); sb.append(alice[n]).append(" ").append(bob[n]).append(" 1\n"); } output.write(sb.toString()); output.flush(); } } class Combinatorics{ private static final long MOD = 998244353L; long[] fac; public Combinatorics(int n){ this.fac = new long[n+1]; fac[0] = 1L; for(int i=1;i<=n;i++) fac[i] = fac[i-1]*i%MOD; } private long powMod(long x, long n){ if(n == 0) return 1L; long t = powMod(x,n/2); if(n%2 == 0) return t*t%MOD; return t*t%MOD*x%MOD; } public long C(int n,int r){ return (fac[n]*powMod(fac[n-r]*fac[r]%MOD,MOD-2))%MOD; } } //Fast Input class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if(st.hasMoreTokens()){ str = st.nextToken("\n"); } else{ str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
1f78db470456bc45e88a3f175c6bb643
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { static long T[][] = {{1, 0, 1}, {3, 2, 1}, {12, 7, 1}, {42, 27, 1}, {153, 98, 1}, {560, 363, 1}, {2079, 1352, 1}, {7787, 5082, 1}, {29392, 19227, 1}, {111605, 73150, 1}, {425866, 279565, 1}, {1631643, 1072512, 1}, {6272812, 4127787, 1}, {24186087, 15930512, 1}, {93489272, 61628247, 1}, {362168442, 238911947, 1}, {407470704, 927891162, 1}, {474237047, 614943428, 1}, {319176974, 87534470, 1}, {131938523, 955113935, 1}, {558075845, 644336680, 1}, {544270478, 253841470, 1}, {209493498, 700054910, 1}, {859106804, 457241336, 1}, {921005664, 6522991, 1}, {366933608, 353887625, 1}, {142064435, 432533537, 1}, {741221694, 874398972, 1}, {297907370, 545598131, 1}, {341102826, 248150916, 1}}; ; static final int INF = 0x3f3f3f3f; static final long LNF = 0x3f3f3f3f3f3f3f3fL; public static void main(String[] args) throws IOException { initReader(); int t=nextInt(); while (t-->0) { int n = nextInt(); if(n==2){ pw.println("1 0 1");continue; } if(n==4){ pw.println("3 2 1");continue; } long a=0,b=0,c=1;Integer mod=998244353; int y=1; for(int i=n;i>=4;i-=2){ long e=1,q=i-1,w=(i-2)/2; for(int j=0;j<w;j++){ e=e*((q-j)); } for(int j=2;j<=w;j++){ e/=j; } if(y%2==1){ a=(a+e)%mod; }else { b=(b+e)%mod; } e=1;q=i-2;w=(i-4)/2; for(int j=0;j<w;j++){ e=e*(q-j); } for(int j=2;j<=w;j++){ e/=j; } if(y%2==1){ b=(b+e)%mod; }else { a=(e+a)%mod; } y++; } if(y%2==1)a++; else b++; a%=mod;b%=mod; pw.println(+T[n/2-1][0]+" "+T[n/2-1][1]+" "+T[n/2-1][2]); } pw.close(); } /***************************************************************************************/ static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter pw; public static void initReader() throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(""); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); // 从文件读写 // reader = new BufferedReader(new FileReader("test.in")); // tokenizer = new StringTokenizer(""); // pw = new PrintWriter(new BufferedWriter(new FileWriter("test1.out"))); } public static boolean hasNext() { try { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } public static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static String nextLine() { try { return reader.readLine(); } catch (Exception e) { return null; } } 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().charAt(0); } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
f6ac0aa309fcdc3af307135873d7d39c
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.awt.Point; import java.util.Scanner; public class C1739 { static long mod = 998244353; static long[][] choose = new long[61][61]; public static void main(String[] args) { for (int n=0; n<=60; n++) { choose[n][0] = 1; choose[n][n] = 1; for (int k=1; k<n; k++) { choose[n][k] = (choose[n-1][k-1] + choose[n-1][k])%mod; } } Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t=0; t<T; t++) { int N = in.nextInt(); Point result = solve(N); System.out.println(result.x + " " + result.y + " 1"); } } static Point solve(int N) { if (N == 2) { return new Point(1, 0); } else if (N == 4) { return new Point(3, 2); } else { Point prev = solve(N-2); long first = choose[N-1][N/2]; long second = choose[N-2][N/2]; long f = (prev.y + first)%mod; long s = (prev.x + second)%mod; return new Point((int) f, (int) s); } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
08d7ec66d729549659fa545d3ff44408
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main{ private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static final int MOD = 998244353; static long[][] dp = new long[65][2]; static long[][] memo = new long[65][65]; public static void main(String[] args) throws IOException { int t = Integer.parseInt(in.readLine()); dp[2][0] = 1; for (int i = 4; i <= 60; i += 2) { dp[i][0] = c(i - 1, i / 2 - 1) + dp[i - 2][1]; dp[i][1] = c(i, i / 2) - 1 - dp[i][0]; } while (t-- > 0) { int n = Integer.parseInt(in.readLine()); System.out.printf("%s %s %s\n", dp[n][0] % MOD, dp[n][1] % MOD, 1); } } private static long c(int m, int n){ if (n == 1) return m; if (m == n) return 1; if (memo[m][n] != 0) return memo[m][n]; return memo[m][n] = c(m - 1, n - 1) + c(m - 1, n); } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
3c51bbd3c650cf6455df4540caa64391
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.util.*; public class p4 { BufferedReader br; StringTokenizer st; BufferedWriter bw; public static void main(String[] args)throws Exception { new p4().run(); } void run()throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw=new BufferedWriter(new OutputStreamWriter(System.out)); solve(); } void solve() throws IOException { int limit=61; int fac[]=new int[limit]; int invfac[]=new int[limit]; fac[0]=1; invfac[0]=1; int mod=998244353; for(int i=0;++i<limit;) { long x=(long)fac[i-1]*i; x%=mod; fac[i]=(int)x; invfac[i]=(int)nPowerM(fac[i], mod-2); } int t=ni(); while(t-->0) { int n=ni(); int n1=n; long ans=0; while(n>0) { long a=(long)fac[n-1]*invfac[n/2]; a%=mod; a*=invfac[n/2-1]; a%=mod; ans+=a; ans%=mod; if(n>4) { a=(long)fac[n-4]*invfac[n/2-3]; a%=mod; a*=invfac[n/2-1]; a%=mod; ans+=a; ans%=mod; } n-=4; } n=n1; if(n>4) { } n=n1; long ans2=(long)fac[n]*invfac[n/2]; ans2%=mod; ans2*=invfac[n/2]; ans2%=mod; ans2-=ans+1; ans2=mod(ans2); System.out.println(ans+" "+ans2+" 1"); } } public long mod(long a) { // int mod=1000000007; int mod=998244353; a%=mod; if(a<0) a+=mod; return a; } public long nPowerM(int n, int m) { if(m==0) return 1L; // int mod=1000000007; int mod=998244353; long ans=nPowerM(n, m/2); ans*=ans; ans%=mod; if(m%2==1) { ans*=n; ans%=mod; } return ans; } /////////////////////////////////////// FOR INPUT /////////////////////////////////////// int[] nai(int n) { int a[]=new int[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;} Integer[] naI(int n) { Integer a[]=new Integer[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;} long[] nal(int n) { long a[]=new long[n]; for(int i=-1;++i<n;)a[i]=nl(); return a;} char[] nac() {char c[]=nextLine().toCharArray(); return c;} char [][] nmc(int n) {char c[][]=new char[n][]; for(int i=-1;++i<n;)c[i]=nac(); return c;} int[][] nmi(int r, int c) {int a[][]=new int[r][c]; for(int i=-1;++i<r;)a[i]=nai(c); return a;} String next() { while (st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();} } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } byte nb() { return Byte.parseByte(next()); } short ns() { return Short.parseShort(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try {str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str; } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
a752e989892c028858553897b9e92949
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; public class CardGame { static long[][] dp; static int mod=998244353; public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); solve(); while(t!=0){ int n=Integer.parseInt(br.readLine()); pr.println(dp[n][0]+" "+dp[n][1]+" "+dp[n][2]); t--; } pr.flush(); pr.close(); } public static void solve(){ dp=new long[61][3]; for(int i=2;i<=60;i++){ dp[i][2]=1; } dp[2][0]=1; dp[2][1]=0; for(int i=4;i<=60;i+=2){ BigInteger total=new BigInteger("1"); for(int j=i/2+1;j<=i;j++){ total=total.multiply(new BigInteger(String.valueOf(j))); } for(int j=1;j<=i/2;j++){ total=total.divide(new BigInteger(String.valueOf(j))); } BigInteger alexWin=new BigInteger("1"); for(int j=1;j<=i-1;j++){ alexWin=alexWin.multiply(new BigInteger(String.valueOf(j))); } for(int j=1;j<=i/2;j++){ alexWin=alexWin.divide(new BigInteger(String.valueOf(j))); } for(int j=1;j<=i/2-1;j++){ alexWin=alexWin.divide(new BigInteger(String.valueOf(j))); } alexWin.mod(new BigInteger(String.valueOf(mod))); dp[i][0]=alexWin.longValue(); dp[i][0]+=dp[i-2][1]; dp[i][0]%=mod; total=total.subtract(new BigInteger("1")).subtract(new BigInteger(String.valueOf(dp[i][0]))); total=total.mod(new BigInteger(String.valueOf(mod))); dp[i][1]=total.longValue(); dp[i][1]%=mod; if(dp[i][1]<0){ dp[i][1]+=mod; } } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
cc62b0b0fa86b0ebc3e05b1ce2167aa7
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.awt.Point; import java.util.Scanner; public class C1739 { static long mod = 998244353; static long[][] choose = new long[61][61]; public static void main(String[] args) { for (int n=0; n<=60; n++) { choose[n][0] = 1; choose[n][n] = 1; for (int k=1; k<n; k++) { choose[n][k] = (choose[n-1][k-1] + choose[n-1][k])%mod; } } Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t=0; t<T; t++) { int N = in.nextInt(); Point result = solve(N); System.out.println(result.x + " " + result.y + " 1"); } } static Point solve(int N) { if (N == 2) { return new Point(1, 0); } else if (N == 4) { return new Point(3, 2); } else { Point prev = solve(N-2); long first = choose[N-1][N/2]; long second = choose[N-2][N/2]; long f = (prev.y + first)%mod; long s = (prev.x + second)%mod; return new Point((int) f, (int) s); } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
e2eebc282921a2e7254ea8afa8295041
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.util.Scanner; public class MyClass { static Scanner in = new Scanner(System.in); static int testCases; static long a, b, c, mod = 998244353L; static void solve() { long x = 1L, y = 0L, mid = 2L; for(int i = 4; i <= (int)a; i += 2) { mid = (mid * 2 * (i - 1)) / (i / 2); x = (mid / 2L) + y; y = mid - x - 1L; } System.out.println(x % mod + " " + y % mod + " 1"); } public static void main(String args[]) { testCases = in.nextInt(); for(int t = 0; t < testCases; ++t) { a = in.nextLong(); solve(); } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
9ecaed0f32fc4684aa334f08e4f4ccb1
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.util.*; public class Main { private static final int mod = 998244353; private static long[][] C; private static void solve(int n){ if(n == 2){ out.println("1 0 1"); return; } if(n == 4){ out.println("3 2 1"); return; } long[] dp = new long[61]; dp[4] = 2; for(int i = 6; i <= n; i+=2){ long total = C[i][i/2]; total %= mod; long alex = C[i-1][i/2 - 1] + dp[i-2]; alex %= mod; dp[i] = (total - alex - 1 + mod) % mod; if(n == i){ out.println(alex + " " + dp[i] + " 1"); } } } private static long[][] getCrTableLong(int n){ long[][] res = new long[n+1][n+1]; for(int i = 0; i <= n; i++){ for (int j = 0; j <= i; j++){ if(j == 0){ res[i][j] = 1L; } else { res[i][j] = res[i-1][j] + res[i-1][j-1]; res[i][j] %= mod; } } } return res; } public static void main(String[] args){ C = getCrTableLong(62); MyScanner scanner = new MyScanner(); int testCount = scanner.nextInt(); for(int testIdx = 1; testIdx <= testCount; testIdx++){ int n = scanner.nextInt(); solve(n); } out.close(); } static void print1DArray(int[] arr){ for(int i = 0; i < arr.length; i++){ out.print(arr[i]); if(i < arr.length - 1){ out.print(' '); } } out.print('\n'); } static void print1DArrayList(List<Integer> arrayList){ for(int i = 0; i < arrayList.size(); i++){ out.print(arrayList.get(i)); if(i < arrayList.size() - 1){ out.print(' '); } } out.print('\n'); } public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
f9994aa906edabad53742b7fe2128166
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.*; public class C { public static void main(String[] args){ FastReader fs=new FastReader(); PrintWriter out=new PrintWriter(System.out); int N=fs.nextInt(); for(int p=0;p<N;p++){ int n=fs.nextInt(); long[][] dp=new long[n+1][3]; dp[2][0]=1; dp[2][1]=0; dp[2][2]=1; for(int i=4;i<=n;i+=2){ dp[i][0] = (nCrMod(i - 1, i / 2) + dp[i - 2][1]) % MOD; dp[i][1] = (nCrMod(i - 2, i / 2) + dp[i - 2][0]) % MOD; dp[i][2] = dp[i - 2][2]; } out.println(dp[n][0] + " " + dp[n][1] + " " + dp[n][2]); } out.close(); } public static final int MOD = 998244353;// ((a + b) % MOD + MOD) % MOD public static long powMod(long base, long exp) { long ans = 1; for (; exp != 0;) { if ((exp & 1) == 1) { ans *= base; ans %= MOD; } base *= base; base %= MOD; exp = exp >> 1; } return ans; } public static long mulMod(long a, long b) { long ans = 0; for (; b != 0;) { if ((b & 1) == 1) { ans += a; ans %= MOD; } a += a; a %= MOD; b >>= 1; } return ans; } static long invMod(long num) { return powMod(num, MOD - 2); // only works if MOD is prime } public static long nCrMod(int n, int r) { if(n < r) return 0; if(r == 0) return 1; long fact[] = new long[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = mulMod(fact[i - 1], i); } return mulMod(fact[n], mulMod(invMod(fact[n - r]), invMod(fact[r]))); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader( new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
7943360948968b6aa6aca9f0ac3e7285
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeMap; public class C { static int[][]a,passed,rem,ans; public static void main(String[]args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); long[][]C=new long[61][61]; long mod=998244353l; for(int i=0;i<C.length;i++)C[i][0]=1; for(int i=1;i<C.length;i++) { for(int j=1;j<=i;j++) { C[i][j]=C[i-1][j]+C[i-1][j-1]; C[i][j]%=mod; } } // out.println(C[7][3]); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[]dr=new int[n/2]; for(int i=0,val=n-1;i<dr.length;i+=2,val-=4) { dr[i]=val; if(i+1<dr.length)dr[i+1]=val-1; } long wn=C[n-1][n/2 -1]; //lex lrgr than dr for(int i=0;i+2<dr.length;i+=2) { wn+=C[dr[i]-3][dr.length-i-3]; wn%=mod; wn+=C[dr[i]-4][dr.length-i-3]; wn%=mod; } long oth =( C[n][n/2] - wn -1 +mod)%mod; out.println(wn+" "+oth+" "+1); } out.close(); } private static int ln(int x) { return (int)Math.log10(x) +1; } private static int dp(int i, int j) { if(i==ans.length)return 0; if(ans[i][j]!=-1)return ans[i][j]; int an=rem[i][j]; if(i<ans.length-1) an=Math.min(an, passed[i+1][1-j]-passed[i][j]+dp(i+1,1-j)); return ans[i][j]=an; } static class Scanner { StringTokenizer st; BufferedReader br; 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 boolean hasNext() {return st.hasMoreTokens();} 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 boolean ready() throws IOException {return br.ready(); } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
4b148be0e921242b8f1731edb7c2d6ef
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.math.BigInteger; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int ii = 0; ii < t; ii++) { int n = in.nextInt(); if(n == 2) { System.out.println("1 0 1"); continue; } BigInteger ba = new BigInteger("0"); for(int i = 0; i < (n + 2) / 4; i++) { BigInteger bb = new BigInteger("1"); for(int j = n - 1 - i * 4; j > (n - i * 4) / 2; j--) { bb = bb.multiply(new BigInteger(j + "")); } for(int j = 1; j < (n - i * 4) / 2; j++) { bb = bb.divide(new BigInteger(j + "")); } ba = ba.add(bb); bb = new BigInteger("1"); if(n - 4 - i * 4 > 0) { for(int j = n - 4 - i * 4; j > (n - i * 4) / 2 - 1; j--) { bb = bb.multiply(new BigInteger(j + "")); } for(int j = 1; j < (n - i * 4) / 2 - 2; j++) { bb = bb.divide(new BigInteger(j + "")); } ba = ba.add(bb); } } int a = ba.mod(new BigInteger("998244353")).intValue(); int c = 1; BigInteger baa = new BigInteger("1"); for(int i = n; i > n / 2; i--) { baa = baa.multiply(new BigInteger(i + "")); } for(int i = 1; i <= n / 2; i++) { baa = baa.divide(new BigInteger(i + "")); } int b = baa.subtract(ba).subtract(new BigInteger("1")).mod(new BigInteger("998244353")).intValue(); System.out.println(a + " " + b + " " + c); } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
8c8093e681fb871c442c38e7f8e230ae
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.util.*; public class assignment { static int mod = 998244353; private static long nCr(int n, int r){ if(r>n-r) r=n-r; long res=1; for(int i=0;i<r;i++){ res*=n-i; res/=i+1; } return res; } public static void main(String args[]) { Scanner s=new Scanner(System.in); int t = s.nextInt(); while(t-->0){ int n = s.nextInt(); long dp[][]=new long[n+1][3]; dp[2][0]=1; dp[2][1]=0; dp[2][2]=1; for(int i=4;i<n+1;i+=2){ dp[i][0]=(nCr(i-1,(i/2))+dp[i-2][1])%mod; dp[i][1]=(nCr(i-2,i/2)+dp[i-2][0])%mod; dp[i][2]=dp[i-2][2]%mod; } System.out.println(dp[n][0]+" "+dp[n][1]+" "+dp[n][2]); } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
ee8b167ea8d905339ab2b6b7543c19aa
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { static long m = 998244353; static long n[][]; public static void main(String[] args) { FastScanner input = new FastScanner(); n = new long[62][62]; n[0][0] = 1; for (int i = 1; i < 62; i++) { n[i][0] = 1; for (int j = 1; j<=i; j++) { n[i][j] = (n[i-1][j-1]+n[i-1][j]); if(n[i][j]>=998244353) { n[i][j]-=998244353; } } } // System.out.println(n[7][2]); int tc = input.nextInt(); work: while (tc-- > 0) { int value = input.nextInt(); long ans[][] = new long[(int)value+1][3]; ans[2][0] = 1; ans[2][1] = 0; ans[2][2] = 1; for (int i = 4; i <=value; i++) { ans[i][0] = (n[i-1][i/2]+ans[i-2][1])%m; ans[i][1] =(n[i-2][i/2]+ans[i-2][0])%m; ans[i][2] = 1; } System.out.println(ans[value][0]+" "+ans[value][1]+" "+ans[value][2]); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
5376c37066f65a57fc933e0c56e34a12
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class CodeForces { /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ public static void solve(int tCase) throws IOException { int n = sc.nextInt(); out.println(dp[n][0]+" "+dp[n][1]+" "+dp[n][2]); } static long[][] dp; private static void preProcess(){ int n = 61; dp = new long[n][3]; _ncr_precompute(60); dp[2] = new long[]{1,0,1}; for(int i=4;i<n;i+=2){ dp[i][0] = (_ncr(i-1,i/2-1) + dp[i-2][1]) % mod; dp[i][1] = (_ncr(i-2,i/2-2) + dp[i-2][0]) % mod; dp[i][2] = ( + _ncr(i,i/2) - dp[i][0] - dp[i][1] + mod + mod) % mod; } } public static void main(String[] args) throws IOException { openIO(); int testCase = 1; testCase = sc.nextInt(); preProcess(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ /*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/ // public static int mod = (int) 1e9 + 7; public static int mod = 998244353; public static int inf_int = (int)1e9; public static long inf_long = (long)2e15; public static void _sort(int[] arr, boolean isAscending) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } public static void _sort(long[] arr, boolean isAscending) { int n = arr.length; List<Long> list = new ArrayList<>(); for (long ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // time : O(1), space : O(1) public static int _digitCount(long num,int base){ // this will give the # of digits needed for a number num in format : base return (int)(1 + Math.log(num)/Math.log(base)); } // time for pre-computation of factorial and inverse-factorial table : O(nlog(mod)) public static long[] factorial , inverseFact; public static void _ncr_precompute(int n){ factorial = new long[n+1]; inverseFact = new long[n+1]; factorial[0] = inverseFact[0] = 1; for (int i = 1; i <=n; i++) { factorial[i] = (factorial[i - 1] * i) % mod; inverseFact[i] = _modExpo(factorial[i], mod - 2); } } // time of factorial calculation after pre-computation is O(1) public static int _ncr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod); } public static int _npr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[n - r] % mod); } // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { while (a>0){ long x = a; a = b % a; b = x; } return b; } // lcm(a,b) * gcd(a,b) = a * b public static long _lcm(long a, long b) { return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _modExpo(long x, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans *= x; ans %= mod; n--; } else { x *= x; x %= mod; n >>= 1; } } return ans; } // function to find a/b under modulo mod. time : O(logn) public static long _modInv(long a,long b){ return (a * _modExpo(b,mod-2)) % mod; } //sieve or first divisor time : O(mx * log ( log (mx) ) ) public static int[] _seive(int mx){ int[] firstDivisor = new int[mx+1]; for(int i=0;i<=mx;i++)firstDivisor[i] = i; for(int i=2;i*i<=mx;i++) if(firstDivisor[i] == i) for(int j = i*i;j<=mx;j+=i) if(firstDivisor[j]==j)firstDivisor[j] = i; return firstDivisor; } static class Pair<K, V>{ K ff; V ss; public Pair(K ff, V ss) { this.ff = ff; this.ss = ss; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return ff.equals(pair.ff) && ss.equals(pair.ss); } @Override public int hashCode() { return Objects.hash(ff, ss); } @Override public String toString(){ return ff.toString()+" "+ss.toString(); } } /*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/ /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException { sc = new FastestReader(); out = new PrintWriter(System.out); } public static void closeIO() throws IOException { out.flush(); out.close(); sc.close(); } private static final class FastestReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public FastestReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastestReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) {} return b; } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); final boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); return neg?-ret: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'); return neg?-ret: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); return neg?-ret:ret; } public String nextLine() throws IOException { final byte[] buf = new byte[(1<<10)]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { din.close(); } } /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/ } /** Some points to keep in mind : * 1. don't use Arrays.sort(primitive data type array) * 2. try to make the parameters of a recursive function as less as possible, * more use static variables. * 3. If n = 5000, then O(n^2 logn) need atleast 4 sec to work * 4. dp[2][n] works faster than dp[n][2] * 5. if split wrt 1 char use '\\' before char: .split("\\."); * 6. while using dp, do not change the state variable for next recursive call apart from the function call itself. * **/
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
f31df04ca8de8718a55c0a258fd482a2
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class C_Edu_Round_136 { public static long MOD = 998244353; static int[] dp; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int T = in.nextInt(); long[] pre = new long[61]; pre[0] = 1; for (int i = 1; i < pre.length; i++) { pre[i] = (pre[i - 1] * i) % MOD; } for (int z = 0; z < T; z++) { int n = in.nextInt(); long win = cal(n, pre); long draw = 1; long lose = (select(n / 2, n, pre) - win - draw + MOD) % MOD; out.println(win + " " + lose + " " + draw); } out.close(); } static long cal(int n, long[] pre) { if (n == 2) { return 1; } long win = select((n / 2) - 1, n - 1, pre); long other = cal(n - 2, pre); long total = select((n - 2) / 2, n - 2, pre); win += (total - other - 1 + MOD) % MOD; win %= MOD; return win; } static long select(int select, int n, long[] pre) { long re = 1; for (int i = n; i > select; i--) { re *= i; re %= MOD; } re *= pow(pre[n - select], (int) MOD - 2); re %= MOD; return re; } static int find(int index, int[] u) { if (u[index] != index) { return u[index] = find(u[index], u); } return index; } static long abs(long 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) % MOD; } else { return (val * ((val * a) % MOD)) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
de032f0efd17fe873036d117350dbeea
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.util.*; import java.math.*; public class A { public static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public static String concat(String s1, String s2) { return new StringBuilder(s1).append(s2).toString(); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static boolean isPrime(int n) { if (n <= 1) return false; else if (n == 2) return true; else if (n % 2 == 0) return false; for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } public class linearArray { int nStudents; int maxIntegers; int l[]; public linearArray(int maxIntegers) { this.maxIntegers = maxIntegers; nStudents = 0; l = new int[maxIntegers]; } // O(1) void insertLast(int x) { if (nStudents >= maxIntegers) return; l[nStudents++] = x; } void insertFirst(int x) { if (nStudents >= maxIntegers) return; for (int i = nStudents; i > 0; i--) { l[i] = l[i - 1]; } l[0] = x; nStudents++; } int linearSearch(int x) { for (int i = 0; i < nStudents; i++) { if (l[i] == x) { return i; } } return -1; } void delete(int x) { int s = linearSearch(x); for (int i = s; i < nStudents - 1; i++) { l[i] = l[i + 1]; } nStudents--; } } static BigInteger nCr(long n, long r) { return fact(n).divide((fact(r).multiply(fact(n - r)))); } // Returns factorial of n static BigInteger fact(long n) { if (n == 0) return new BigInteger(1 + ""); BigInteger res = new BigInteger(1 + ""); for (int i = 2; i <= n; i++) res = res.multiply(new BigInteger(i + "")); return res; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t1 = sc.nextInt(); outer: while (t1-- > 0) { long x1 = 0, x2 = 0; int n = sc.nextInt(); long dp[][] = new long[61][2]; dp[2][0] = 1; dp[2][1] = 0; rec(n,dp); out.println(dp[n][0] + " "+dp[n][1]+" "+1); } out.close(); } static void rec(int n, long[][] dp) { if (n == 2) return; rec(n - 2, dp); dp[n][0] = (Long.parseLong(nCr(n - 1, n / 2 - 1).toString()) + dp[n - 2][1]) % 998244353; // System.out.println(dp[n - 2][1]); // System.out.println(nCr(n - 1, n / 2 - 1)); // System.out.println(dp[n][0]); dp[n][1] = (Long.parseLong(nCr(n, n / 2 ).toString()) -dp[n][0]-1) % 998244353; // System.out.println(nCr(n, n / 2 )); // System.out.println(dp[n - 2][0]); // System.out.println(dp[n][1]); } static class Pair implements Comparable<Pair> { long first; long second; public Pair(long first, long second) { this.first = first; this.second = second; } public int compareTo(Pair p) { if (first != p.first) return Long.compare(first, p.first); else if (second != p.second) return Long.compare(second, p.second); else return 0; } } static class Tuple implements Comparable<Tuple> { long first; long second; long third; public Tuple(long a, long b, long c) { first = a; second = b; third = c; } public int compareTo(Tuple t) { if (first != t.first) return Long.compare(first, t.first); else if (second != t.second) return Long.compare(second, t.second); else if (third != t.third) return Long.compare(third, t.third); else return 0; } } static final Random random = new Random(); static void shuffleSort(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = random.nextInt(n), temp = a[r]; a[r] = a[i]; a[i] = temp; } Arrays.sort(a); } static class Scanner { StringTokenizer st; BufferedReader br; 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()); } 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(); } long[] readArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
df30afafa4352364c77d125cba68d831
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
/* Author:-crazy_coder- */ import java.io.*; import java.util.*; public class cp{ static long mod=998244353; static int ans=0; static int[] par=new int[100005]; static int[] rank=new int[100005]; static BufferedReader br=new BufferedReader (new InputStreamReader(System.in)); static PrintWriter pw=new PrintWriter(System.out); public static void main(String[] args)throws Exception{ int T=Integer.parseInt(br.readLine()); // int t=1; comp(); while(T-->0){ solve(); } pw.flush(); } public static void solve()throws Exception{ String[] str=br.readLine().split(" "); int n=Integer.parseInt(str[0]); // int c=Integer.parseInt(str[1]); long[][] dp=new long[n+1][3]; dp[2][0]=1; dp[2][1]=0; dp[2][2]=1; recurse(n,dp); pw.println(dp[n][0]+" "+dp[n][1]+" "+dp[n][2]); } public static void recurse(int n,long[][] dp){ if(n==2)return; recurse(n-2,dp); dp[n][0]=(NCR(n-1,n/2)+dp[n-2][1])%mod; dp[n][1]=(NCR(n-2,n/2)+dp[n-2][0])%mod; dp[n][2]=(dp[n-2][2])%mod; } public static long NCR(int n,int r){ if(r==0||r==n)return 1; return (fac[n]*invfact[r]%mod)*invfact[n-r]%mod; } static long[] fac=new long[100]; static long[] invfact=new long[100]; public static void comp(){ fac[0]=1; invfact[0]=1; for(int i=1;i<100;i++){ fac[i]=(fac[i-1]*i)%mod; invfact[i]=modInverse(fac[i]); } } public static long modInverse(long n){ return power(n,mod-2); } public static long power(long x,long y){ long res=1; x=x%mod; while(y>0){ if((y&1)==1)res=(res*x)%mod; y=y>>1; x=(x*x)%mod; } return res; } //*************************************DSU************************************ */ public static void initialize(int n){ for(int i=1;i<=n;i++){ par[i]=i; rank[i]=1; } } public static void union(int x,int y){ int lx=find(x); int ly=find(y); if(lx!=ly){ if(rank[lx]>rank[ly]){ par[ly]=lx; }else if(rank[lx]<rank[ly]){ par[lx]=ly; }else{ par[lx]=ly; rank[ly]++; } } } public static int find(int x){ if(par[x]==x){ return x; } int temp=find(par[x]); par[x]=temp; return temp; } //************************************DSU END********************************** */ public static boolean isPresent(ArrayList<Long> zero,long val){ for(long x:zero){ if(x==val)return true; } return false; } public static class Pair implements Comparable<Pair>{ int val; int k; Pair(int val,int k){ this.val=val; this.k=k; } public int compareTo(Pair o){ return this.val-o.val; } } public static int countDigit(int x){ return (int)Math.log10(x)+1; } //****************************function to find all factor************************************************* public static ArrayList<Long> findAllFactors(long num){ ArrayList<Long> factors = new ArrayList<Long>(); for(long i = 1; i <= num/i; ++i) { if(num % i == 0) { //if i is a factor, num/i is also a factor factors.add(i); factors.add(num/i); } } //sort the factors Collections.sort(factors); return factors; } //*************************** function to find GCD of two number******************************************* public static long gcd(long a,long b){ if(b==0)return a; return gcd(b,a%b); } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
138d45ecad14d68a034ef1ba625987e9
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.util.*; import java.math.*; 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 = (((su % mod) * ((long) i % mod)) % mod); } while(su<0) su+=mod; 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 BigInteger factorial2(int N) { // Initialize result BigInteger f = new BigInteger("1"); // Or BigInteger.ONE // Multiply f with 2, 3, ...N for (int i = 2; i <= N; i++) f = f.multiply(BigInteger.valueOf(i)); return f; } public static void solve() { int t = s.nextInt(); long a[] = new long[61]; long b[] = new long[61]; long c[] = new long[61]; Arrays.fill(c, 1); mod = 998244353; Map<Integer, Integer> mp = new HashMap<>(); TreeSet<Integer> set = new TreeSet<>(); for (int i = 2; i <= 60; i += 2) { BigInteger p1 = factorial2(i); BigInteger p2 = factorial2(i/2); BigInteger total = p1.divide(p2.multiply(p2)) ; total= total.subtract(BigInteger.valueOf(1)); int tot = total.remainder(BigInteger.valueOf(mod)).intValue(); BigInteger p3 = factorial2(i-1) ; BigInteger p4 = factorial2(i/2 -1) ; a[i] = ( p3 .divide(p4.multiply(p2) )).remainder(BigInteger.valueOf(mod)).intValue(); // while(a[i]<0) // a[i]+=mod; // a[i] = p3 / p4); // a[i] = (a[i] / factorial(i / 2))% mod; a[i] = (a[i] + b[i - 2]) % mod; b[i] = (tot - a[i] )%mod; while(b[i]<0) b[i]+=mod; } while(t-->0) { int n = s.nextInt(); w.println(a[n]+" "+b[n]+" "+c[n]); } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
bd5e96f21471a95d7e58d3e276b46aee
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C_Card_Game { static Scanner in = new Scanner(); static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans = new StringBuilder(); static int testCases, c, n, m; static int a[]; static long T[][] = {{1, 0, 1}, {3, 2, 1}, {12, 7, 1}, {42, 27, 1}, {153, 98, 1}, {560, 363, 1}, {2079, 1352, 1}, {7787, 5082, 1}, {29392, 19227, 1}, {111605, 73150, 1}, {425866, 279565, 1}, {1631643, 1072512, 1}, {6272812, 4127787, 1}, {24186087, 15930512, 1}, {93489272, 61628247, 1}, {362168442, 238911947, 1}, {407470704, 927891162, 1}, {474237047, 614943428, 1}, {319176974, 87534470, 1}, {131938523, 955113935, 1}, {558075845, 644336680, 1}, {544270478, 253841470, 1}, {209493498, 700054910, 1}, {859106804, 457241336, 1}, {921005664, 6522991, 1}, {366933608, 353887625, 1}, {142064435, 432533537, 1}, {741221694, 874398972, 1}, {297907370, 545598131, 1}, {341102826, 248150916, 1}}; ; static ArrayList1<Long> stack[]; static void solve(int t) { ans.append(T[n][0]).append(" ").append(T[n][1]).append(" ").append(T[n][2]); if (t != testCases) { ans.append("\n"); } } public static void main(String[] Priya) throws IOException { testCases = in.nextInt(); for (int t = 0; t < testCases; ++t) { n = in.nextInt(); n = (n / 2) - 1; solve(t + 1); } out.print(ans.toString()); out.flush(); } static class Tree { long sum[]; public Tree(long[] sum) { this.sum = sum; } void build_tree(int index, int l, int r) { if (l == r) { sum[index] = a[l]; return; } int mid = (l + r) / 2; build_tree(2 * index, l, mid); build_tree(2 * index + 1, mid + 1, r); sum[index] = sum[index * 2] + sum[2 * index + 1]; } void update(int index, int l, int r, int pos, long value) { if (l > pos || r < pos) { return; } if (l == r && l == pos) { sum[index] += value; return; } int mid = (l + r) / 2; if (mid >= pos) { update(2 * index, l, mid, pos, value); } else { update(2 * index + 1, mid + 1, r, pos, value); } sum[index] = sum[2 * index] + sum[2 * index + 1]; } long query(int index, int L, int R, int l, int r) { if (L > r || R < l) { return 0; } if (L >= l && R <= r) { return sum[index]; } int mid = (L + R) / 2; long x = query(2 * index, L, mid, l, r); long y = query(2 * index + 1, mid + 1, R, l, r); return x + y; } } static long pow(long value, long n) { long result = 1L; while (n > 0L) { if (n % 2L == 1L) { result *= value; } value *= value; n /= 2L; } return result; } static long gcd(long n1, long n2) { if (n2 != 0) { return gcd(n2, n1 % n2); } else { return n1; } } static int search(long a[], long x, int last) { int i = 0, j = last; while (i <= j) { int mid = i + (j - i) / 2; if (a[mid] == x) { return mid; } if (a[mid] < x) { i = mid + 1; } else { j = mid - 1; } } return -1; } static void swap(long a[], int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void reverse(long a[]) { int n = a.length; for (int i = 0; i < n / 2; ++i) { swap(a, i, n - i - 1); } } static long max(long a[], int i, int n, long max) { if (i > n) { return max; } max = Math.max(a[i], max); return max(a, i + 1, n, max); } static long min(long a[], int i, int n, long max) { if (i > n) { return max; } max = Math.min(a[i], max); return max(a, i + 1, n, max); } static void printArray(long a[]) { for (long i : a) { System.out.print(i + " "); } System.out.println(); } static boolean isSmaller(String str1, String str2) { int n1 = str1.length(), n2 = str2.length(); if (n1 < n2) { return true; } if (n2 < n1) { return false; } for (int i = 0; i < n1; i++) { if (str1.charAt(i) < str2.charAt(i)) { return true; } else if (str1.charAt(i) > str2.charAt(i)) { return false; } } return false; } static String sub(String str1, String str2) { if (isSmaller(str1, str2)) { String t = str1; str1 = str2; str2 = t; } String str = ""; int n1 = str1.length(), n2 = str2.length(); int diff = n1 - n2; int carry = 0; for (int i = n2 - 1; i >= 0; i--) { int sub = (((int) str1.charAt(i + diff) - (int) '0') - ((int) str2.charAt(i) - (int) '0') - carry); if (sub < 0) { sub = sub + 10; carry = 1; } else { carry = 0; } str += String.valueOf(sub); } for (int i = n1 - n2 - 1; i >= 0; i--) { if (str1.charAt(i) == '0' && carry > 0) { str += "9"; continue; } int sub = (((int) str1.charAt(i) - (int) '0') - carry); if (i > 0 || sub > 0) { str += String.valueOf(sub); } carry = 0; } return new StringBuilder(str).reverse().toString(); } static String sum(String str1, String str2) { if (str1.length() > str2.length()) { String t = str1; str1 = str2; str2 = t; } String str = ""; int n1 = str1.length(), n2 = str2.length(); int diff = n2 - n1; int carry = 0; for (int i = n1 - 1; i >= 0; i--) { int sum = ((int) (str1.charAt(i) - '0') + (int) (str2.charAt(i + diff) - '0') + carry); str += (char) (sum % 10 + '0'); carry = sum / 10; } for (int i = n2 - n1 - 1; i >= 0; i--) { int sum = ((int) (str2.charAt(i) - '0') + carry); str += (char) (sum % 10 + '0'); carry = sum / 10; } if (carry > 0) { str += (char) (carry + '0'); } return new StringBuilder(str).reverse().toString(); } static long detect_sum(int i, long a[], long sum) { if (i >= a.length) { return sum; } return detect_sum(i + 1, a, sum + a[i]); } static String mul(String num1, String num2) { int len1 = num1.length(); int len2 = num2.length(); if (len1 == 0 || len2 == 0) { return "0"; } int result[] = new int[len1 + len2]; int i_n1 = 0; int i_n2 = 0; for (int i = len1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1.charAt(i) - '0'; i_n2 = 0; for (int j = len2 - 1; j >= 0; j--) { int n2 = num2.charAt(j) - '0'; int sum = n1 * n2 + result[i_n1 + i_n2] + carry; carry = sum / 10; result[i_n1 + i_n2] = sum % 10; i_n2++; } if (carry > 0) { result[i_n1 + i_n2] += carry; } i_n1++; } int i = result.length - 1; while (i >= 0 && result[i] == 0) { i--; } if (i == -1) { return "0"; } String s = ""; while (i >= 0) { s += (result[i--]); } return s; } static class Node<T> { T data; Node<T> next; public Node() { this.next = null; } public Node(T data) { this.data = data; this.next = null; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Node<T> getNext() { return next; } public void setNext(Node<T> next) { this.next = next; } @Override public String toString() { return this.getData().toString() + " "; } } static class ArrayList1<T> { Node<T> head, tail; int len; public ArrayList1() { this.head = null; this.tail = null; this.len = 0; } int size() { return len; } boolean isEmpty() { return len == 0; } int indexOf(T data) { if (isEmpty()) { throw new ArrayIndexOutOfBoundsException(); } Node<T> temp = head; int index = -1, i = 0; while (temp != null) { if (temp.getData() == data) { index = i; } i++; temp = temp.getNext(); } return index; } void add(T data) { Node<T> newNode = new Node<>(data); if (isEmpty()) { head = newNode; tail = newNode; len++; } else { tail.setNext(newNode); tail = newNode; len++; } } void see() { if (isEmpty()) { throw new ArrayIndexOutOfBoundsException(); } Node<T> temp = head; while (temp != null) { System.out.print(temp.getData().toString() + " "); //out.flush(); temp = temp.getNext(); } System.out.println(); //out.flush(); } void inserFirst(T data) { Node<T> newNode = new Node<>(data); Node<T> temp = head; if (isEmpty()) { head = newNode; tail = newNode; len++; } else { newNode.setNext(temp); head = newNode; len++; } } T get(int index) { if (isEmpty() || index >= len) { throw new ArrayIndexOutOfBoundsException(); } if (index == 0) { return head.getData(); } Node<T> temp = head; int i = 0; T data = null; while (temp != null) { if (i == index) { data = temp.getData(); } i++; temp = temp.getNext(); } return data; } void addAt(T data, int index) { if (index >= len) { throw new ArrayIndexOutOfBoundsException(); } Node<T> newNode = new Node<>(data); int i = 0; Node<T> temp = head; while (temp.next != null) { if (i == index) { newNode.setNext(temp.next); temp.next = newNode; } i++; temp = temp.getNext(); } // temp.setNext(temp); len++; } void popFront() { if (isEmpty()) { //return; throw new ArrayIndexOutOfBoundsException(); } if (head == tail) { head = null; tail = null; } else { head = head.getNext(); } len--; } void removeAt(int index) { if (index >= len) { throw new ArrayIndexOutOfBoundsException(); } if (index == 0) { this.popFront(); return; } Node<T> temp = head; int i = 0; Node<T> n = new Node<>(); while (temp != null) { if (i == index) { n.next = temp.next; temp.next = n; break; } i++; n = temp; temp = temp.getNext(); } tail = n; --len; } void clearAll() { this.head = null; this.tail = null; } } static void merge(long a[], int left, int right, int mid) { int n1 = mid - left + 1, n2 = right - mid; long L[] = new long[n1]; long R[] = new long[n2]; for (int i = 0; i < n1; i++) { L[i] = a[left + i]; } for (int i = 0; i < n2; i++) { R[i] = a[mid + 1 + i]; } int i = 0, j = 0, k1 = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) { a[k1] = L[i]; i++; } else { a[k1] = R[j]; j++; } k1++; } while (i < n1) { a[k1] = L[i]; i++; k1++; } while (j < n2) { a[k1] = R[j]; j++; k1++; } } static void sort(long a[], int left, int right) { if (left >= right) { return; } int mid = (left + right) / 2; sort(a, left, mid); sort(a, mid + 1, right); merge(a, left, right, mid); } static class Scanner { BufferedReader in; StringTokenizer st; public Scanner() { in = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } String nextLine() throws IOException { return in.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void close() throws IOException { in.close(); } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
b70b997c9998a226f85a03cfe500836d
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.util.*; public class C { static class Pair { int f;int s; // Pair(){} Pair(int f,int s){ this.f=f;this.s=s;} } static class sortbyfirst implements Comparator<Pair> { public int compare(Pair a,Pair b) { return a.f-b.f; } } static class Fast { BufferedReader br; StringTokenizer st; public Fast() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArray1(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (IOException e) { e.printStackTrace(); } return str; } } /* static long noOfDivisor(long a) { long count=0; long t=a; for(long i=1;i<=(int)Math.sqrt(a);i++) { if(a%i==0) count+=2; } if(a==((long)Math.sqrt(a)*(long)Math.sqrt(a))) { count--; } return count; }*/ static boolean isPrime(long a) { for (long i = 2; i <= (long) Math.sqrt(a); i++) { if (a % i == 0) return false; } return true; } static void primeFact(int n) { int temp = n; HashMap<Integer, Integer> h = new HashMap<>(); for (int i = 2; i * i <= n; i++) { if (temp % i == 0) { int c = 0; while (temp % i == 0) { c++; temp /= i; } h.put(i, c); } } if (temp != 1) h.put(temp, 1); } static void reverseArray(int a[]) { int n = a.length; for (int i = 0; i < n / 2; i++) { a[i] = a[i] ^ a[n - i - 1]; a[n - i - 1] = a[i] ^ a[n - i - 1]; a[i] = a[i] ^ a[n - i - 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 void sort(long [] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static int max(int a,int b) { return a>b?a:b; } static int min(int a,int b) { return a<b?a:b; } static long mul(long a, long b) { return (a*b)%mod; } static final int mod=998244353; static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { if(n<=0||n<k) return 0; return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static int ncr(int n ,int r) { int res,i; res=1; for( i=1;i<=r;i++) { res=(res*(n-i+1))/i; } return res; } //static long a=0;static long b=0; static long rec(int i,int turn,int n) { if(i==0) return 0; long a=0; if(turn==1) { a+=(nCk(i-1,i/2)+rec(i-2,1-turn,n))%mod; } else a+=(nCk(i-2,i/2)+rec(i-2,1-turn,n))%mod; return a%mod; } static long rec1(int i,int turn,int n) { if(i<=0) return 0; long a=0; if(turn==0) { a+=(nCk(i-2,i/2)+rec(i-2,1-turn,n))%mod; } else a+=(nCk(i-1,i/2)+rec(i-2,1-turn,n))%mod; return a%mod; } public static void main(String args[]) throws IOException { Fast sc = new Fast(); PrintWriter out = new PrintWriter(System.out); int t1 = sc.nextInt(); precompFacts(); while (t1-- > 0) { int n=sc.nextInt(); /* if(n>2) { int n1 = n/2; long ans=0; for (int i = 0; i < n1-1; i++) { ans=(ans%mod+nCk(n-((2*i)+1),(n/2)-i))%mod; } long tot=nCk(n,n/2)%mod; long a1=0; if(tot-ans<0) a1=tot-ans+mod; else a1=tot-ans; // out.println(tot+" "+ans); if(n>4) out.println(ans-1+" "+a1+" "+1); else { out.println(ans + " " +(tot-ans) + " " + 1); } } else { out.println("1 0 1"); }*/ int dp[][]=new int[n+1][2]; long alex=rec(n,1,n); long bor=rec1(n,0,n); out.println(alex+" "+bor+" "+1); } out.close(); } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
fb055b0f304846ac78eba29afb24a7a5
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.util.StringTokenizer; /** * @author freya * @date 2022/9/6 **/ public class C { public static Reader in; public static PrintWriter out; public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); in = new Reader(); solve(); out.close(); } static void solve(){ int t = in.nextInt(); long mod = 998244353; long[][] c = new long[61][61]; for(int i = 0;i<61;i++){ c[i][0] = 1; for(int j = 1;j<61&&j<=i;j++){ c[i][j] = (c[i-1][j-1] + c[i-1][j]) % mod; } } long[] f = new long[61]; f[2] = 1; f[4] = 3; for(int i = 6;i<61;i+=2){ f[i] = c[i-1][i/2-1] + c[i-4][i/2-3] + f[i-4]; f[i] %= mod; } while (t-->0){ int n = in.nextInt(); long tmp = (c[n][n>>1] + mod - 1 - f[n]) % mod; out.println(f[n] + " " + tmp + " " + 1); } } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } long nextLong() { return Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
b184a90d2d5a1bd64582146906e3bd1e
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.util.*; import java.io.*; // res.append("Case #"+(p+1)+": "+hh+" \n"); ////*************************************************************************** /* 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_Card_Game{ public static void main(String[] args) { FastScanner s= new FastScanner(); PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); long mod=998244353; int size=65; long facts[]= new long[size]; facts[0]=1; facts[1]=1; for(int i=2;i<size;i++){ facts[i]=(i*facts[i-1])%mod; } long infacts[]= new long[size]; for(int i=0;i<size;i++){ infacts[i]=modpower(facts[i],mod-2,mod); } int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); long alice=0; long bob=0; long draw=1; int curr=n; while(curr>4){ int half=curr/2;; long alpha=find(facts,infacts,curr-1,half,mod); alice=(alice+alpha)%mod; alpha=find(facts,infacts,curr-2,half-2,mod); bob=(bob+alpha)%mod; alpha=find(facts,infacts,curr-3,half-2,mod); bob=(bob+alpha)%mod; alpha=find(facts,infacts,curr-4,half-1,mod); alice=(alice+alpha)%mod; curr-=4; } if(curr==2){ alice=(alice+1)%mod; } else if(curr==4){ alice=(alice+3)%mod; bob=(bob+2)%mod; } res.append(alice+" "+bob+" "+draw+"\n"); p++;} out.println(res); out.close(); } private static long find(long[] facts, long[] infacts, int first, int second,long mod) { long alpha=facts[first]; alpha=(alpha*infacts[second])%mod; alpha=(alpha*infacts[(first-second)])%mod; return alpha; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
e54d4a79dc7d565b6968a2bce164f4a8
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
//package codeforces.edu136; import java.io.*; import java.util.*; import static java.lang.Math.*; public class C { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); solve(in.nextInt()); //solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static int n; static long mod = 998244353L; static long[] factor; static void solve(int testCnt) { factor = new long[61]; factor[0] = 1; for(int i = 1; i <= 60; i++) { factor[i] = factor[i - 1] * i % mod; } for (int testNumber = 0; testNumber < testCnt; testNumber++) { n = in.nextInt(); long total = mCk(n, n / 2); long draw = 1; long alex = 0; // for(int v = n; v >= 1; v -= 4) { // int m = v - 1; // int k = n / 2 - (n - v) / 2 - 1; // alex = (alex + mCk(m, k)) % mod; // } for(int turn = 1; turn <= n / 2; turn++) { int remain = 0, pick = 0; if(turn % 2 != 0) { remain = n - (turn - 1) * 2 - 1; pick = n / 2 - (turn - 1) - 1; } else { remain = n - (turn - 1) * 2 - 2; pick = n / 2 - (turn - 1) - 2; } if(pick >= 0) { alex = (alex + mCk(remain, pick)) % mod; } } long boris = (total - 1 - alex + mod * 2) % mod; out.println(alex + " " + boris + " " + draw); } out.close(); } static long mCk(int m, int k) { return factor[m] * modInv(factor[k], mod) % mod * modInv(factor[m - k], mod) % mod; } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
b7b35486358958c2664068ba3f56793a
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.math.BigInteger; import java.util.Arrays; import java.util.StringTokenizer; import java.util.function.DoubleToIntFunction; public class Round22 { static BigInteger mod=new BigInteger(998244353+""); public static void main(String[] args) throws IOException { Scanner scanner=new Scanner(System.in); int t=scanner.nextInt(); while(t-->0){ int n=scanner.nextInt(); BigInteger win=earn(n).mod(mod); BigInteger loss=C(n,n/2).subtract(earn(n)).subtract(new BigInteger("1")).mod(mod); System.out.println(win.toString()+" "+loss.toString()+" "+1); } } public static BigInteger earn(int n){ if (n==2) return new BigInteger("1"); if (n==4) return new BigInteger("3"); if (n==6) return new BigInteger("12"); BigInteger out=C(n-1,n/2-1); out=out.subtract(new BigInteger("1")); BigInteger inc=C(n-2,n/2-1).subtract(earn(n-2)); out=out.add(inc); return out; } public static BigInteger C(int p, int c){ return (fac(p).divide(fac(c).multiply(fac(p-c)))); } public static BigInteger fac(int f){ if (f==0||f==1) return BigInteger.valueOf(1); return BigInteger.valueOf(f).multiply(fac(f-1)); } // -----------------------------------stuff----------------------------------------------------- public static void print(int[][] all) { for (int[] i : all) System.out.println(Arrays.toString(i)); } 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
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
4e13f2ebb30155c8c80bc5dd788fa0cf
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.math.BigInteger; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.*; public class app { public static long m; static int mod = 998244353; static int inf = (int) 1e9; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); //int t=1; long gh[][]=new long[61][2]; Gr1zler: gh[2][0]=1; gh[2][1]=0; gh[4][0]=3; gh[4][1]=2; for(int i=6;i<61;i+=2){ long fg=1; for(int j=i/2+1;j<i;j++){ fg*=j; fg/=j-i/2; } gh[i][0]=(fg+gh[i-2][1])%mod; fg=1; for(int j=i/2+1;j<=i-2;j++){ fg*=j; fg/=j-i/2; } gh[i][1]=(fg+gh[i-2][0])%mod; } for (int qw = 0; qw < t; qw++) { int as=sc.nextInt(); System.out.println(gh[as][0]+" "+gh[as][1]+" "+1); } out.close(); } //out.println(Arrays.toString(d).replace(",","").replace("]","").replace("[","")); static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a * b / gcd(a, b); } static void sort(int[] a) { int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[i]; } static void sort(long[] a) { int n = a.length; Long[] b = new Long[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[i]; } 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; } } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
cce740a0a97c65ed9b338e1d7e40d84b
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
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.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static long[][] dp = new long[61][2]; public static void main(String[] args) { long mod = 998244353l; dp[2][0] = 1; dp[2][1] = 0; for (int i = 4; i <= 60; i++) { dp[i][0] = (ncr(i - 1, (i / 2) - 1) % mod + dp[i - 2][1]) % mod; dp[i][1] = (ncr(i - 2, (i / 2) - 2) % mod + dp[i - 2][0]) % mod; } try { FastReader in = new FastReader(); FastWriter out = new FastWriter(); int testCases = in.nextInt(); StringBuilder sb = new StringBuilder(); while (testCases-- > 0) { int n = in.nextInt(); sb.append(dp[n][0] + " " + dp[n][1] + " 1\n"); } out.print(sb); out.close(); } catch (Exception e) { return; } } static long ncr(int n, int r) { long ans = 1; int i; for (i = 1; i <= r; i++) { ans *= n - r + i; ans /= i; } return ans; } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
15dc81ffea69daedb47bf8d3d35690f3
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader bf; static PrintWriter out; static Scanner sc; static StringTokenizer st; // static long mod = (long)(1e9+7); static long mod = 998244353; static long fact[]; static long inverse[]; public static void main (String[] args)throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new Scanner(System.in); fact = new long[65]; inverse = new long[65]; fact[0] = 1; inverse[0] = 1; for(int i = 1;i<fact.length;i++){ fact[i] = (fact[i-1] * i)%mod; inverse[i] = binaryExpo(fact[i], mod-2); } int t = nextInt(); while(t-->0){ solve(); } out.flush(); } public static void solve()throws IOException{ int n = nextInt(); long[]winner = new long[61]; long[]loser = new long[61]; for(int i = 2;i<=60;i+=2){ long total = (nck(i,i/2)); long alex = (nck(i-1,i/2)); alex = (alex + loser[i-2])%mod; winner[i] = alex; // if(i == 4){ // out.println(alex + " " + (loser[i-2])); // } loser[i] = (((total - ((alex + 1)%mod)) + mod)%mod); } // out.println(loser[2]); out.println(winner[n] + " " + loser[n] + " " + (1)); // alex = (alex + (n-1))%mod; } public static int compare(String a , String b){ if(a.compareTo(b) < 0)return -1; if(a.compareTo(b) > 0)return 1; return 0; } public static void req(long l,long r){ out.println("? " + l + " " + r); out.flush(); } public static long sum(int node ,int left,int right,int tleft,int tright,long[]tree){ if(left >= tleft && right <= tright)return tree[node]; if(right < tleft || left > tright)return 0; int mid = (left + right )/2; return sum(node * 2, left,mid,tleft,tright,tree) + sum(node * 2 + 1 ,mid + 1, right,tleft,tright,tree); } public static void req(int l,int r){ out.println("? " + l + " " + r); out.flush(); } public static int[] bringSame(int u,int v ,int parent[][],int[]depth){ if(depth[u] < depth[v]){ int temp = u; u = v; v = temp; } int k = depth[u] - depth[v]; for(int i = 0;i<=18;i++){ if((k & (1<<i)) != 0){ u = parent[u][i]; } } return new int[]{u,v}; } public static void findDepth(List<List<Integer>>list,int cur,int parent,int[]depth,int[][]p){ List<Integer>temp = list.get(cur); p[cur][0] = parent; for(int i = 0;i<temp.size();i++){ int next = temp.get(i); if(next != parent){ depth[next] = depth[cur]+1; findDepth(list,next,cur,depth,p); } } } public static int lca(int u, int v,int[][]parent){ if(u == v)return u; for(int i = 18;i>=0;i--){ if(parent[u][i] != parent[v][i]){ u = parent[u][i]; v = parent[v][i]; } } return parent[u][0]; } public static void plus(int node,int low,int high,int tlow,int thigh,int[]tree){ if(low >= tlow && high <= thigh){ tree[node]++; return; } if(high < tlow || low > thigh)return; int mid = (low + high)/2; plus(node*2,low,mid,tlow,thigh,tree); plus(node*2 + 1 , mid + 1, high,tlow, thigh,tree); } public static boolean allEqual(int[]arr,int x){ for(int i = 0;i<arr.length;i++){ if(arr[i] != x)return false; } return true; } public static long helper(StringBuilder sb){ return Long.parseLong(sb.toString()); } public static int min(int node,int low,int high,int tlow,int thigh,int[][]tree){ if(low >= tlow&& high <= thigh)return tree[node][0]; if(high < tlow || low > thigh)return Integer.MAX_VALUE; int mid = (low + high)/2; // println(low+" "+high+" "+tlow+" "+thigh); return Math.min(min(node*2,low,mid,tlow,thigh,tree) ,min(node*2+1,mid+1,high,tlow,thigh,tree)); } public static int max(int node,int low,int high,int tlow,int thigh,int[][]tree){ if(low >= tlow && high <= thigh)return tree[node][1]; if(high < tlow || low > thigh)return Integer.MIN_VALUE; int mid = (low + high)/2; return Math.max(max(node*2,low,mid,tlow,thigh,tree) ,max(node*2+1,mid+1,high,tlow,thigh,tree)); } public static long[] help(List<List<Integer>>list,int[][]range,int cur){ List<Integer>temp = list.get(cur); if(temp.size() == 0)return new long[]{range[cur][1],1}; long sum = 0; long count = 0; for(int i = 0;i<temp.size();i++){ long []arr = help(list,range,temp.get(i)); sum += arr[0]; count += arr[1]; } if(sum < range[cur][0]){ count++; sum = range[cur][1]; } return new long[]{sum,count}; } public static long findSum(int node,int low, int high,int tlow,int thigh,long[]tree,long mod){ if(low >= tlow && high <= thigh)return tree[node]%mod; if(low > thigh || high < tlow)return 0; int mid = (low + high)/2; return((findSum(node*2,low,mid,tlow,thigh,tree,mod) % mod) + (findSum(node*2+1,mid+1,high,tlow,thigh,tree,mod)))%mod; } public static boolean allzero(long[]arr){ for(int i =0 ;i<arr.length;i++){ if(arr[i]!=0)return false; } return true; } public static long count(long[][]dp,int i,int[]arr,int drank,long sum){ if(i == arr.length)return 0; if(dp[i][drank]!=-1 && arr[i]+sum >=0)return dp[i][drank]; if(sum + arr[i] >= 0){ long count1 = 1 + count(dp,i+1,arr,drank+1,sum+arr[i]); long count2 = count(dp,i+1,arr,drank,sum); return dp[i][drank] = Math.max(count1,count2); } return dp[i][drank] = count(dp,i+1,arr,drank,sum); } public static void help(int[]arr,char[]signs,int l,int r){ if( l < r){ int mid = (l+r)/2; help(arr,signs,l,mid); help(arr,signs,mid+1,r); merge(arr,signs,l,mid,r); } } public static void merge(int[]arr,char[]signs,int l,int mid,int r){ int n1 = mid - l + 1; int n2 = r - mid; int[]a = new int[n1]; int []b = new int[n2]; char[]asigns = new char[n1]; char[]bsigns = new char[n2]; for(int i = 0;i<n1;i++){ a[i] = arr[i+l]; asigns[i] = signs[i+l]; } for(int i = 0;i<n2;i++){ b[i] = arr[i+mid+1]; bsigns[i] = signs[i+mid+1]; } int i = 0; int j = 0; int k = l; boolean opp = false; while(i<n1 && j<n2){ if(a[i] <= b[j]){ arr[k] = a[i]; if(opp){ if(asigns[i] == 'R'){ signs[k] = 'L'; } else{ signs[k] = 'R'; } } else{ signs[k] = asigns[i]; } i++; k++; } else{ arr[k] = b[j]; int times = n1 - i; if(times%2 == 1){ if(bsigns[j] == 'R'){ signs[k] = 'L'; } else{ signs[k] = 'R'; } } else{ signs[k] = bsigns[j]; } j++; opp = !opp; k++; } } while(i<n1){ arr[k] = a[i]; if(opp){ if(asigns[i] == 'R'){ signs[k] = 'L'; } else{ signs[k] = 'R'; } } else{ signs[k] = asigns[i]; } i++; k++; } while(j<n2){ arr[k] = b[j]; signs[k] = bsigns[j]; j++; k++; } } public static long nck(int n,int k){ return ((fact[n] * (inverse[n-k])%mod) * inverse[k])%mod; } public static long binaryExpo(long base,long expo){ if(expo == 0)return 1; long val; if(expo%2 == 1){ val = (binaryExpo(base, expo/2)); val = (val * val)%mod; val = (val * base)%mod; } else{ val = binaryExpo(base, expo/2); val = (val*val)%mod; } return (val%mod); } public static boolean isSorted(int[]arr){ for(int i =1;i<arr.length;i++){ if(arr[i] < arr[i-1]){ return false; } } return true; } //function to find the topological sort of the a DAG public static boolean hasCycle(int[]indegree,List<List<Integer>>list,int n,List<Integer>topo){ Queue<Integer>q = new LinkedList<>(); for(int i =1;i<indegree.length;i++){ if(indegree[i] == 0){ q.add(i); topo.add(i); } } while(!q.isEmpty()){ int cur = q.poll(); List<Integer>l = list.get(cur); for(int i = 0;i<l.size();i++){ indegree[l.get(i)]--; if(indegree[l.get(i)] == 0){ q.add(l.get(i)); topo.add(l.get(i)); } } } if(topo.size() == n)return false; return true; } // function to find the parent of any given node with path compression in DSU public static int find(int val,int[]parent){ if(val == parent[val])return val; return parent[val] = find(parent[val],parent); } // function to connect two components public static void union(int[]rank,int[]parent,int u,int v){ int a = find(u,parent); int b= find(v,parent); if(a == b)return; if(rank[a] == rank[b]){ parent[b] = a; rank[a]++; } else{ if(rank[a] > rank[b]){ parent[b] = a; } else{ parent[a] = b; } } } // public static int findN(int n){ int num = 1; while(num < n){ num *=2; } return num; } // code for input public static void print(String s ){ System.out.print(s); } public static void print(int num ){ System.out.print(num); } public static void print(long num ){ System.out.print(num); } public static void println(String s){ System.out.println(s); } public static void println(int num){ System.out.println(num); } public static void println(long num){ System.out.println(num); } public static void println(){ System.out.println(); } public static int Int(String s){ return Integer.parseInt(s); } public static long Long(String s){ return Long.parseLong(s); } public static String[] nextStringArray()throws IOException{ return bf.readLine().split(" "); } public static String nextString()throws IOException{ return bf.readLine(); } public static long[] nextLongArray(int n)throws IOException{ String[]str = bf.readLine().split(" "); long[]arr = new long[n]; for(int i =0;i<n;i++){ arr[i] = Long.parseLong(str[i]); } return arr; } public static int[][] newIntMatrix(int r,int c)throws IOException{ int[][]arr = new int[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Integer.parseInt(str[j]); } } return arr; } public static long[][] newLongMatrix(int r,int c)throws IOException{ long[][]arr = new long[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Long.parseLong(str[j]); } } return arr; } static class pair{ int one; int two; pair(int one,int two){ this.one = one ; this.two =two; } } public static long gcd(long a,long b){ if(b == 0)return a; return gcd(b,a%b); } public static long lcm(long a,long b){ return (a*b)/(gcd(a,b)); } public static boolean isPalindrome(String s){ int i = 0; int j = s.length()-1; while(i<=j){ if(s.charAt(i) != s.charAt(j)){ return false; } i++; j--; } return true; } // these functions are to calculate the number of smaller elements after self public static void sort(int[]arr,int l,int r){ if(l < r){ int mid = (l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); smallerNumberAfterSelf(arr, l, mid, r); } } public static void smallerNumberAfterSelf(int[]arr,int l,int mid,int r){ int n1 = mid - l +1; int n2 = r - mid; int []a = new int[n1]; int[]b = new int[n2]; for(int i = 0;i<n1;i++){ a[i] = arr[l+i]; } for(int i =0;i<n2;i++){ b[i] = arr[mid+i+1]; } int i = 0; int j =0; int k = l; while(i<n1 && j < n2){ if(a[i] < b[j]){ arr[k++] = a[i++]; } else{ arr[k++] = b[j++]; } } while(i<n1){ arr[k++] = a[i++]; } while(j<n2){ arr[k++] = b[j++]; } } public static String next(){ while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bf.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static String nextLine(){ String str = ""; try { str = bf.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // use some math tricks it might help // sometimes just try to think in straightforward plan in A and B problems don't always complecate the questions with thinking too much differently // always use long number to do 10^9+7 modulo // if a problem is related to binary string it could also be related to parenthesis // *****try to use binary search(it is a very beautiful thing it can work in some of the very unexpected problems ) in the question it might work****** // try sorting // try to think in opposite direction of question it might work in your way // if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+d or a,b,c,d in general // if the question is to much related to left and/or right side of any element in an array then try monotonic stack it could work. // in range query sums try to do binary search it could work // analyse the time complexity of program thoroughly // anylyse the test cases properly // if we divide any number by 2 till it gets 1 then there will be (number - 1) operation required // try to do the opposite operation of what is given in the problem //think about the base cases properly //If a question is related to numbers try prime factorisation or something related to number theory // keep in mind unique strings //you can calculate the number of inversion in O(n log n) // in a matrix you could sometimes think about row and cols indenpendentaly. // Try to think in more constructive(means a way to look through various cases of a problem) way. // observe the problem carefully the answer could be hidden in the given test cases itself. (A, B , C); // when we have equations like (a+b = N) and we have to find the max of (a*b) then the values near to the N/2 must be chosen as (a and b); // give emphasis to the number of occurences of elements it might help. // if a number is even then we can find the pair for each and every number in that range whose bitwise AND is zero. // if a you find a problem related to the graph make a graph // There is atleast one prime number between the interval [n , 3n/2]; // If a problem is related to maths then try to form an mathematical equation. // you can create any sum between (n * (n + 1)/2) with first n natural numbers.
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output
PASSED
b0b041565930ed648ca8b24ca68bb443
train_109.jsonl
1664462100
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
512 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Codeforces { public static PrintWriter out; public static Scanner sc; public static void main(String[] args) throws IOException { sc = new Scanner(System.in); out = new PrintWriter(System.out); solA[2] = 1; solB[2] = 0; solD[2] = 1; for (int i = 4; i <= 60; i+=2) { long total = binomial(i, i/2); solA[i] = total / 2 + solB[i-2]; solB[i] = total - solA[i] - 1; solD[i] = 1; } int t = 1; t = sc.nextInt(); while(t-->0) solve(); out.flush(); out.close(); } static long[] solA = new long[61]; static long[] solB = new long[61]; static long[] solD = new long[61]; public static void solve() throws IOException { int n = sc.nextInt(); out.println((solA[n]%998244353) + " " + (solB[n]%998244353) + " " + solD[n]%998244353); } private static long binomial(long n, long k) { if (k>n-k) k=n-k; long b=1; for (int i = 1, m = (int) n; i<=k; i++, m--) b=b*m/i; return b; } //greatest common divisor public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static void sort(int[] arr) { sort(arr, Comparator.naturalOrder()); } public static void sort(int[] arr, Comparator orderStyle) { //because Arrays.sort() uses quicksort which is dumb //Collections.sort() uses merge sort ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls, orderStyle); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } public static void sort(long[] arr) { sort(arr, Comparator.naturalOrder()); } public static void sort(long[] arr, Comparator orderStyle) { //because Arrays.sort() uses quicksort which is dumb //Collections.sort() uses merge sort ArrayList<Long> ls = new ArrayList<Long>(); for(long x: arr) ls.add(x); Collections.sort(ls, orderStyle); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static class Scanner { StringTokenizer st; BufferedReader br; 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());} //public char nextChar() throws IOException {return next();} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Java 8
standard input
[ "combinatorics", "constructive algorithms", "dp", "games" ]
63fc2fb08d248f8ccdb3f5364c96dac1
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
1,500
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
standard output