Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all 40121 articles
Browse latest View live

shknum august challenge

$
0
0

how can use power function pow in the codechef


SMPAIR - Editorial

$
0
0

Problem link : contestpractice

Difficulty : CakeWalk

Pre-requisites : Sorting

Problem : Given a sequence a1, a2, ..., aN. Find the smallest possible value of ai + aj, where 1 ≤ i< jN

Explanation

This problem was the easiest one in the set and it was intended to enable everybody to get some points.

How to get 13 points

Here you have only two integers a1 and a2, so the only possible sum will be a1+a2.

How to get 60 points

The constraints were designed in such a way that you can iterate through all the possible pairs (i, j), where 1 ≤ i< jN and check for every obtained sum, whether it's the minimal one.

How to get 100 points

The answer is basically the sum of the minimal and the second-minimal element in the array. So you can simply iterate through all the numbers, keeping track of the minimal and the second-minimal number. Or if your programming language has built-in sorting, you can act even simpler, because after the sorting of the array in increasing order, the required minimal and the second-minimal will be the first and the second elements of the sorted array.

Related links

  • Reference in the built-in sorting for C++ users

Solutions : settertester

https://www.codechef.com/problems/HS08TEST

$
0
0

Whenever run this code i get wrong answer can someone help me in notifying the error: code:

include<iostream>

include<iomanip>

using namespace std; int main() { int x,i; float bal; cout<<"\nEnter the balance amount"; cin>>bal; cout<<"\nEnter withdraw amount"; cin>>x; if(x%5==0 && x+0.5<bal) { bal=bal-x-0.50; cout<<setprecision(2)<<bal; } else cout<<setprecision(2)<<bal; return 0; }

T23 - Editorial

$
0
0

PROBLEM LINK:

[Contest] T23

Author:Nandishwar Garg

DIFFICULTY:

SIMPLE

PROBLEM:

You are given an array of size N. You have to find every possible subset of the elements in array. Then we have to check 3 conditions on these subsets:

  1. It should not be empty.
  2. It should not have any element in subset which divide other elements present in subset except 1.
  3. It should not have duplicate elements.

If it satisfies all the conditions then print yes otherwise print no.

EXPLANATION:

Suppose the array elements are 1,2 and 3. The subsets of these elements are {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}.

  1. None of these subsets are empty
  2. No element other than 1 is dividing another element
  3. No duplicate element is present.

So, you have to print yes.

Taking another example, the array elements are 2 and 4. The subsets of following elements are {2}, {4} and {2,4}.

  1. None of these subsets are empty
  2. In {2,4}, 2 is dividing 4 so it doesn’t satisfy the condition

Thus you have to print no as the output.

AUTHOR'S SOLUTIONS:

Author's solution can be found here

plz solve this one need the solution as urgent as posible

$
0
0

find the number of positive integers less than n that have a multiplicative inverse with respect to n

Constraints N < 10^9

Input Format The only line of the input is a single integer N which is divisible by no prime number larger than 13.

Output One line containing an integer that gives the number of integers less than N that have a multiplicative inverse

Can anyone post the editorial of MCQ game problem (T-24)from Innerve Summer of Code Challenge ?

$
0
0

I have gone through a lot of successful submissions for MCQ game problem but still not able to understand them ,specially why mod has been changed to mod-2.Please help.

how to run a for loop

$
0
0

i am unable to use loops in my programming how can i know make uses of loop in programming

by JAVA or C or C++

$
0
0

A number (N) of lines (extending to infinity) in both directions are drawn on a plane. The lines are specified by the angle (positive or negative) made with the x axis (in degrees). It may be assumed that the different lines are not coincident (they do not overlap each other). The objective is to determine the number of parallelograms in the plane formed by these lines.

for ex:If the lines are given with an angle of 10, 70, 30 and 30.


median of n numbers without using array

$
0
0

java program to find median of n numbers without using array

codevita contest by tcs

$
0
0

Codu And Sum Love Problem Description ```

Scanner sc = new Scanner(System.in);

long sum = 0;

int N = sc.nextInt();

for (int i = 0; i < N; i++) {

final long x = sc.nextLong(); // read input

String str = Long.toString((long) Math.pow(1 << 1, x));

str = str.length() > 2 ? str.substring(str.length() - 2) : str;

sum += Integer.parseInt(str);

}

System.out.println(sum%100);

```

Given N number of x’'s, perform logic equivalent of the above Java code and print the output

Constraints 1<=N<=10^7 0<=x<=10^18

Input Format First line contains an integer N

Second line will contain N numbers delimited by space

Output Number that is the output of the given code by taking inputs as specified above

Explanation Example 1

Input 4 8 6 7 4 Output 64

Example 2

Input

3

1 2 3

Output

14

SUMTRIAN : NZEC in C#

LISDIGIT - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Alexey Zayakin
Testers:Hasan Jaddouh
Editorialist:Alexey Zayakin

DIFFICULTY:

Cakewalk

PREREQUISITES:

Constructive algorithms, longest increasing subsequence

PROBLEM:

For an $n$-digit number $x$ we define the $LIS$ array as follows: $i$-th element of the array is the length of the longest strictly increasing subsequence of numbers $x$ digits that ends with the $i$-th digit.

Given the $LIS$ array of some $n$-digit number, find any $x$ that corresponds to this $LIS$ array.

QUICK EXPLANATION:

We can interpret the array in the input as array of digits of $x$, i.e. the $i$-th digit of $x$ will be equal to the $i$-th element of the $LIS$ array.

EXPLANATION:

Let's denote the $i$-th digit of number $x$ with $d_i$, i.e. $x = \overline{d_1 d_2 \dots d_n}$.

What does it means that $LIS[i] = k$? It means that there exists a sequence $p_1 < p_2 < \dots < p_{k - 1} < i$ such that $LIS[p_1] = 1, LIS[p_2] = 2, \dots, LIS[p_{k - 1}] = k - 1$ and digits $d_{p_1}, d_{p_2}, \dots, d_{p_{k - 1}}, d_i$ form a strictly increasing sequence. The simplest way to make this sequence increasing is to simply assign $d_{p_1} = 1, d_{p_2} = 2, \dots, d_{p_{k - 1}} = k - 1, d_i = k$ or in other words $d_j = LIS[j]$.

Given that $n \le 9$, it follows that $1 \le LIS[i] \le 9$ and thus all the values of the $LIS$ array are indeed non-zero digits.

Time Complexity:

$\mathcal{O}(n)$ per test case.

Bonus:

Can you solve this problem with constraints $n \le 100$?

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter
Tester

KTHMAX - Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:Rishabh

Tester:Kevin Charles Atienza

Editorialist:Vaibhav Tulsyan

DIFFICULTY:

Medium

PREREQUISITES:

Stacks, Binary Search

PROBLEM:

For an array of $N$ integers, you are asked to answer $M$ queries. In each query, you are asked the first number in the $p^{th}$ sub-array, after sorting all numbers in each sub-array in descending order and then sorting the sub-arrays in descending order.

QUICK EXPLANATION:

For each $i (1 \le i \le N)$, calculate the number of subarrays for which $a_i$ is the maximum element. Store indexes $j (1 \le j \lt i)$ and $k (i + 1 \le k \le N)$, such that: - $a_j > a_i$ - $a_k > a_i$ - All integers between $i$ and $j$ are smaller than $a_i$. - All integers between $i$ and $k$ and smaller than $a_i$. Number of subarrays for which $a_i$ is max is equal to $(i - j) * (k - i)$. Sort the elements in descending order and maintain a cumulative sum of no. of subarrays uptil the $i^{th}$ index. Use binary search to find the value associated with the $p^{th}$ sub-array.

EXPLANATION:

Subtask 1:

  • Iterate over all possible sub-arrays of length $1, 2, 3, ... , N$.
  • After fixing the end-points, iterate over the array to find the maximum element.
  • Store the maximum element of each subarray in a list $L$.
  • Sort $L$ in descending order.
  • The maximum element of the $p^{th}$ sub-array would be the $p^{th}$ element in this list $L$.

Complexity: $O(N^3 + N^2.log_2(N) + M)$

This naive solution would time out for Subtasks 2 and 3 and would hence fetch only $20$ points.

Subtask 2:

  • Maintain a list $L$ to store the maximum values of all sub-arrays.
  • Iterate over all possible sub-arrays by fixing the end-points of the array, say $X$ and $Y$.
  • Keep a running maximum element present in all sub-arrays whose left boundary is $X$.
  • For each sub-array, store the newly computed maximum in the list $L$.
  • Sort $L$ in descending order.
  • The maximum element of the $p^{th}$ sub-array would be the $p^{th}$ element in this list $L$.

Complexity: $O(N^2 + N^2.log_2(N) + M)$

This solution would give a total of $50$ points.

Subtask 3:

In order to find the number of subarrays whose max is $a_i$, we can make a useful observation. For each $i$, we can determine a left boundary $j$ and a right boundary $k$ such all integers $a_x (j \lt x \lt i)$ and $a_y (i \lt x \lt k)$ are less than or equal to $a_i$. In other words, let $[j+1 .. k-1]$ represent the longest segment in which no element is greater than $a_i$. Then, the no. of sub-arrays in which $a_i$ is maximum is equal to $(i - j) * (k - i)$.

How do we find these boundaries for all $i$ in $O(N)$ or $O(N.log(N))$ time?

We will use a stack to find the boundaries. Let's try to find only the left boundary for each $i$ first. If the current element being processed, say $Z$, is less than or equal to the element at the top of the stack, say $T$, then the left boundary of $Z$ would be the index of $T$. Otherwise, we keep popping elements from the stack until we find a suitable boundary.

Pseudo-code: stack = [-1] left_boundary = [null for i in (1..n)] for i in [1..n]: while (stack is not empty) and (stack.top <= a[i]): stack.pop() left_boundary[i] = stack.top stack.push(i)

Similarly, we can also compute the right boundary for each $i$.

We have computed the boundaries of all $i$ in $O(N)$ time. This was the slowest step in our previous naive solutions. Now, we need to store the no. of subarrays for which each $a_i$ is maximum, and sort this list in descending order of $a_i$.

The next question is: how do we find the maximum element associated with the $p^{th}$ sub-array?

Since $N$ can be $10^5$, the number of subarrays can be of the order $10^10$. A linear search would result in TLE.

If we maintain a cumulative sum of the no. of subarrays processed in this sorted list, we will get a monotonically increasing sequence. We can apply binary search on this sequence to find the required answer.

Pseudo-code: data = [(a[1], count[1]), (a[2], count[2]), ... , (a[k], count[k])] for i in [1..len(data) - 1]: count[i + 1] += count[i] for query in [1..m]: p = input() low = 0, high = n while high - low > 1: mid = (low + high) >> 1 if count[mid] > p: low = mid else: high = mid return a[high]

Complexity: $O(N + log_2(N)$

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution can be found here.

Tester's solution can be found here.

Editorialist's solution can be found here.

BASE - Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:Kevin Charles Atienza

Tester:Kevin Charles Atienza

Editorialist:Vaibhav Tulsyan

DIFFICULTY:

Easy-Medium

PREREQUISITES:

None

PROBLEM:

Given an integer $N$, find the number of integer bases $B$, such that the base-$B$ representation of $N$ starts with a $1$.

QUICK EXPLANATION:

In base $B$, a number with $(K + 1)$ digits is in the range $[B^K, B^{(K + 1)})$. It starts with the digit $1$ if and only if it is in the range $[B^K, 2.B^K)$. Hence, for a base $B$ containing $(K + 1)$ digits, we need to find the no. of bases satisfying $floor({N/2}^{1/K}) \lt B \le N^{1/K}$. The different lengths of bases we need to check are $log_2(N)$, which is at max $40$.

EXPLANATION:

For $N = 0$, the answer is $0$, as no base $B$ representation of $0$ can start with $1$. For $N = 1$, the answer is "INFINITY", as $1$ written in any base $B$ starts with a $1$.

Naive Approach:

We can iterate over all bases in the range $[2, N]$, find the base-$B$ representation of $N$ and check if it starts with $1$.

Pseudo-code: if N == 0: return 0 if N == 1: return "INFINITY" ans = 0 for base in [2..N]: num = n while num > 1: num /= base digit %= base if digit == 1: ans += 1 return ans

This approach is too slow and would pass only Subtask 1.

Expected Solution:

Let's say that a base in consideration $B$ contains $(K + 1)$ digits. Such a base can represent numbers in range: $[B^K, B^{(K + 1)})$. We want the first digit to be equal to $1$. A number $N$ written in base $B$ starts with $1$ if and only if it is in the range $[B^K, 2.B^K)$. This implies, $floor({N/2}) \lt B^K \le N$, which is equivalent to $floor({N/2}^{1/K}) \lt B \le N^{1/K}$. For each value of $K$, we can now find out the bases $B$ that we require - that is, the values of $B$ satisfying this inequality.

Since the maximum value of $N$ in the given problem is $10^{12}$, the highest length of the base that is possible is at most $40$.

Pseudo-code: if N == 0: return 0 if N == 1: return "INFINITY"

ans = 0 for length in [2..40]: val = f(N, length) - f(N / 2, length) ans += val return ans

function f(N, length): x = int(round(pow(N, 1 / length))) while pow(x, length) < N: x += 1 while pow(x, length) > N: x -= 1 return x

Complexity: $O(T * (40.\alpha))$, where $\alpha$ is the complexity of the $pow(a, b)$ function, where $b$ is a floating point number less than $1$.

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution can be found here.

Tester's solution can be found here.

Editorialist's solution can be found here.

ANKTRAIN - Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:Ankit Srivastava

Tester:Kevin Charles Atienza

Editorialist:Vaibhav Tulsyan

DIFFICULTY:

CAKEWALK

PREREQUISITES:

None

PROBLEM:

Given a pattern of arrangement of berths in a train, find the train partner of a given berth number. The pattern repeats for every 8 berths.

QUICK EXPLANATION:

Maintain a map that stores neighbouring berth of the first 8 berths. For a given berth number $N$, find it's neighbour $M$ that lies in the same compartment, say $C$. In order to do this, find the berth equivalent to $N$ in the $1^{st}$ compartment and it's neighbour $M'$. Add appropriate offset to find equivalent berth of $M'$ in the compartment $C$. The berth number of the number is: $N - N \% 8 + M'$.

EXPLANATION:

Subtask 1:

The approach used for this subtask will be extended and used for subtask 2. From the constraints of Subtask 1, we know that $1 \le N \le 8$. This means that we are dealing with only 1 compartment.

Let's store the neighbours of each berth - this can be hard-coded in the program, as there are only 8 berths.

neighbours = { 0 -> "4LB", 1 -> "5MB", 2 -> "6UB", 3 -> "1LB", 4 -> "2MB", 5 -> "3UB", 6 -> "8SU", 7 -> "7SL" }

For a given value of $N$, we just need to fetch the value from the neighbours table for $(N - 1)$ since our table has 0-indexed keys. This can be implemented using a list/array/hashmap.

Subtask 2:

Note that the pattern repeats after every 8 berths - hence, group of berths [9..16] is identical to group [1..8], and [17..24] is also identical to [1..8]. Thus, all we have to do is find the equivalent neighbour ($M'$) of $N$ in the $1^{st}$ compartment and add an offset to this neighbour. Let's say $N$ was present in compartment $C$. The first berth of that compartment would have the number $N - (N \% 8)$. Hence, the berth number of the neighbour would be: $(N - (N \% 8) + M')$.

Note: Since we're working with integers under a given Modulo, we are using 0-indexing for our neighbours map for simplicity.

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution can be found here.

Tester's solution can be found here.

Editorialist's solution can be found here.


KIRLAB - Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:Roman Kachur

Tester:Kevin Charles Atienza

Editorialist:Vaibhav Tulsyan

DIFFICULTY:

Easy-medium

PREREQUISITES:

Prime-factorization, GCD, Sieve of Eratosthenes, Dynamic Programming

PROBLEM:

Given a sequence of integers, finding its longest sub-sequence such that the GCD of the every consecutive integer is greater than $1$.

QUICK EXPLANATION:

Pre-compute the smallest prime-factor of all integers from $1$ to $10^7$ using the Sieve of Eratosthenes. Use dynamic programming to store the maximum length of the required sub-sequence such that consecutive integers have common prime-factors. $f(i, P)$ stores the maximum length of the sub-sequence uptil index $i$ such that the last-used prime factor is $P$. Note: In the DP table, we only need to maintain the max length for each prime uptil now - without storing the information for each and every index.

EXPLANATION:

Subtask 1:

For this subtask, the constraint on the no. of integers ($N$) in the array is: $1 \le N \le 10^3$. For each index $i$, we can find number of indexes $j (j \lt i)$ such that $gcd(a_i, a_j) > 1$. Let's call this value $V_i$. Our goal is to maximize $V_i$ over all $i$ from $1$ to $N$.

The complexity of this solution is: $O(N^2 * log(max(a_i)))$.

This solution would fetch 30 points.

Subtask 2:

When we say that we want to find the longest sub-sequence that had $gcd > 1$, it is equivalent to saying we want to find the longest sub-sequence which has a common prime-factor. This is true owing to the nature of the $gcd$ function.

  • Approach For each index $i$ in the given array, we can store the set $S$ of prime factors of all integers we have seen upto this index. For each of these prime factors $P$, we can maintain a value $count_{P}$ - the number of integers that have $P$ as a prime factor.

Our final answer would be: $max(count_{P})$, across all $P$ present in $S$ after going through the entire array.

  • Implementation
  • We will need to prime-factorize each integer in the array.

We first use sieve to find the smallest prime factor of all integers in range [1..10^7].

Pseudo-code for pre-computing smallest prime factors using sieve: smallest_prime_factor = [1 for all ints uptil 10^7] # initialize for i in [2..10^7]: if smallest_prime_factor[i] == 1: for j in [i..10^7]: smallest_prime_factor[j] = i j += i

Pseudo-code for prime-factorization of a number: prime_factors = set() while number != 1: prime_factors.add(smallest_prime_factor[number]) number /= smallest_prime_factor[number]

Now, we can use dynamic programming to store the maximum possible sub-sequence length that ends at index $i$, such that $a_i$ contains $P$ as a prime factor. Let the prime factors of $a_i$ be $p_1, p_2, p_3, ... , p_K$. For each $p_j$, let's say the maximum possible sub-sequence length such that the previous selected number had a common prime factor was $l_j$. We choose the maximum length $M$ equal to $max(l_j) (1 \le j \le K)$. We update $dp(p_j)$ with the value $M$. While performing updates, we maintain a global maximum - the maximum $M$ calculated uptil now.

  • Complexity
  • Pre-computation using sieve: $O(X*log(log(X)))$, where $X = 10^7$.
  • Computation of max length sub-sequence: $O(N * log_2(Y))$, where $Y$ is the number in the array with maximum no. of prime factors.

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution can be found here.

Tester's solution can be found here.

Editorialist's solution can be found here.

CHEFCCYL - Editorial

$
0
0

Ah, I could have used the [hide][/hide] function if I knew it earlier. This would make editorials clearer, I think.

PROBLEM LINK:

Practice

Contest

Author:Full name

Tester:Full name

Editorialist:Full name

DIFFICULTY:

CAKEWALK, SIMPLE, EASY, MEDIUM or HARD. Intermediate levels like SIMPLE-EASY, EASY-MEDIUM, MEDIUM-HARD are also possible.

PREREQUISITES:

Greedy, DP, Math etc. Ideally with the links to Wikipedia

PROBLEM:

View Content

QUICK EXPLANATION:

Let's call the endpoints of additional edges "keypoint"s. The topology of keypoints form a cycle, so we can handle distance queries of keypoints quickly. For a general query, let's say it's from vertex $v_1$ on cycle $c_1$ to vertex $v_2$ on cycle $c_2$. The path goes through some keypoint $k_1$ on cycle $c_1$ and some $k_2$ on cycle $c_2$. Since every cycle has at most $2$ keypoints, we enumerate $k_1$ and $k_2$, and thus answer queries on constant time.

EXPLANATION:

Subtask 1

This is a shortest path problem on a graph with $M=A_1+A_2+\dots+A_N$ vertices and $M+1$ edges. We can run Dijkstra's Algorithm for each query. The time complexity for heap-optimized Dijkstra's Algorithm is $O(M\log M)$. So total complexity is $O(QM\log M)$.

Subtask 2

Querying on one cycle

Consider the easier problem: you have one cycle and you want to answer distance queries. Let's number the vertices $1,2,\dots,N$, and suppose the cycle is $1-2-3-\dots-N-1$. For any $i,j(i < j)$, the only simple paths between $i,j$ are:

  • $i\to (i+1)\to(i+2)\to\dots\to j$, length $l_1$;
  • $i\to (i-1)\to\dots\to 1\to N\to (N-1)\to\dots\to (j+1)\to j$, length $l_2$.

The two paths

Let's precompute $d_i$ as the length of path $1\to 2\to\dots\to i$. Then $l_1=d_j-d_i$. Since $l_2+l_1$ is the length of the whole cycle, $l_2$ can be easily calculated, too. We return the smaller number between $l_1$ and $l_2$, and answer the query in $O(1)$ time.

Querying on keypoints

Let's call the endpoints of additional edges "keypoint"s. Consider how to answer distance queries between keypoints. We construct a new graph $C$ whose vertices are only the keypoints. For two keypoints:

  • if they are connected by an additional edge, we add this edge to $C$;
  • if they are in the same cycle, we query that cycle and get their distance $d$ in the cycle, then connect them with an edge of weight $d$.

Cycle graph $C$

The resulting graph $C$ is a cycle: every vertex has degree $2$ and $C$ is connected. Thus we can easily handle distance queries on $C$. Also, $C$ preserves distances on the original graph. So we can answer distance queries about endpoints in $O(1)$ time.

The final solution

First, using the above algorithms we can support distance queries on one cycle and on keypoints.

Suppose there is a query $(V_1,C_1,V_2,C_2)$. Since $C_1\ne C_2$, their shortest path must pass through some keypoint in cycle $C_1$, suppose it's $k_1$; it also passes through some keypoint in cycle $C_2$, say $k_2$. Then the shortest path has length $dis(V_1,k_1)+dis(k_1,k_2)+dis(k_2,V_2)$, and the smallest this value among all $(k_1,k_2)$'s is the answer. The three $dis()$'s can be obtained in $O(1)$ time. Each cycle has at most $2$ keypoints, so there are at most $4$ pairs of $(k_1,k_2)$ that we need to enumerate.

The time complexity is $O(Q+M)$, where $M=A_1+A_2+\dots+A_N$.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found [here][333]. Tester's solution can be found [here][444].

RELATED PROBLEMS:

[333]: The link is provided by admins after the contest ends and the solutions are uploaded on the CodeChef Server. [444]: The link is provided by admins after the contest ends and the solutions are uploaded on the CodeChef Server

BRIBETR - Editorial

$
0
0

Author:Kamil Debowski
Tester:Niyaz Nigmatullin
Editorialist:Kamil Debowski

DIFFICULTY:

MEDIUM

PREREQUISITES:

two pointers, dynamic programming

PROBLEM

...

SLOWER SOLUTION

Let's first solve the problem in O(N2).

It's useful to imagine the tournament as the binary tree, just like one provided in the statement. For each bear b there are only O(log(N)) vertices where he can get (all ancestors of this leaf). We can create a two-dimensional array dp[log[N]][N] where dp[r][b] denotes the minimum possible cost of getting the bear b to the r-th ancestor of the leaf where b starts. To compute dp[r][b] we need values dp[r-1][1..N] — then we consider all possible matches that can happen in the r-th ancestor of the leaf with b. Let's also see how to consider a single match in O(1). If we know that that b1 can get so far with cost dp[r-1][b1] (i.e. Limak must bribe at least this number of referees to ensure that b1 gets to the level r-1) and b2 can get so far with cost dp[r-1][b2], then:

  • If b1 > b2, the bear b1 can get further with the cost dp[r-1][b1] + dp[r-1][b2], i.e. in the code we do dp[r][b1] = min(dp[r][b1], dp[r-1][b1] + dp[r-1][b2])
  • If b1 > b2 but b1 - b2 ≤ K, the bear b2 can get further with the cost dp[r-1][b1] + dp[r-1][b2] + 1
  • ... (similarly if b2 > b1)

It might seem that this approach has complexity O(N2 * log(N)) but we don't iterate over all pairs of bears in each of log(N) levels (depths). You can notice that for any two bears (b1, b2) they can fight in only one vertex (their LCA), so only once we will consider a match between those two. Since there are O(N2) pairs of bears and considering one match takes O(1), we get O(N2) in total. See the implementation below:

const int INF = 1e9 + 5;
int h, k;
scanf("%d%d", &h, &k);
int n = 1 << h;
vector<int> skill(n);
for(int i = 0; i < n; ++i)
    scanf("%d", &skill[i]);
vector<int> dp(n, 0);
for(int level = 0; level < h; ++level) {
    int block = 1 << level;
    vector<int> old = dp;
    dp = vector<int>(n, INF);
    for(int start = 0; start < n; start += 2 * block)
        for(int i = start; i < start + block; ++i)
            for(int j = start + block; j < start + 2 * block; ++j)
                for(int rep = 0; rep < 2; ++rep) {
                    swap(i, j);
                    if(skill[j] < skill[i])
                        dp[i] = min(dp[i], old[i] + old[j]);
                    else if(skill[j] <= skill[i] + k)
                        dp[i] = min(dp[i], old[i] + old[j] + 1);
                }

}
int ans = dp[0];
if(ans >= INF) ans = -1;
printf("%d\n", ans);

FAST SOLUTION

To get O(N*log2(N)) or faster, we should do one more thing. When we consider matches that can happen in some vertex x (i.e. in some way we want to compute for each bear the cost of getting him to the vertex x), we can take all dp values from the children of x (i.e. for each bear the cost of getting him to one of children of x), we can merge the two arrays faster than in O(size2). So far, if the subtree of the left child had leaves b1, b2, ..., bp, and the subtree of the right child had leaves bp+1, bp+2, ..., b2*p (remember that leaves denote bears that could get to this vertex), then we considered O(p2) matches separately. Instead, we can build some data structure on costs of b1, ..., bp, and then for each of bi in bp+1, bp+2, ..., b2*p consider two things:

  • This bi can advance further by winning a match with some bj among b1, ..., bp, but only if skilli> skillj. So we can ask the data structure about the smallest possible cost of some bear from bp+1, bp+2, ..., b2*p with skill smaller than skilli.
  • Or this bi can advance further by winning a match with someone stronger by at most K, what of course will increase the total cost by 1. Here we should ask the data structure about the smallest possible cost of some between with skill in interval [skilli + 1, skilli + K].

Such approach gives the O(N*log2(N)) complexity (see the tester's code) and should get AC. It's possible to achieve O(N*log(N)) with two pointers though. More information will be provided tomorrow (but you can see the setter's code now).

AUTHOR'S AND TESTER'S SOLUTIONS:


Setter's solution can be found here.
Tester's solution can be found here.

WEICOM - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Trung Nguyen
Tester:Oleksandr Kulkov
Editorialist:Oleksandr Kulkov

DIFFICULTY:

MEDIUM

PREREQUISITES:

None

PROBLEM:

$n$ players participated in tournaments. Each player compete with each other once. Winner earns $1$ point, loser earns $0$ points. After the tournament player that won $g_i$ games is awarded by $g_i^2$ money. You have to check if it is possible that overall earns of players equals $k$.

QUICK EXPLANATION:

TODO

EXPLANATION:

First thing we should look at is the fact that sum of points earned by all players equals $\dfrac{n(n-1)}{2}$. TODO

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found [here][333]. Tester's solution can be found [here][444].

RELATED PROBLEMS:

[333]: The link is provided by admins after the contest ends and the solutions are uploaded on the CodeChef Server. [444]: The link is provided by admins after the contest ends and the solutions are uploaded on the CodeChef Server

Wrong Problem in the Contest 'Coding Hours'

$
0
0

In the contest COHR2018, the problem 'Chef And His Algorithm' is probably wrong.

The problem asks us to compute the minimum length of a string which consists of all the permutations of the given string, if the latter has all unique characters. This problem is the same as the Minimal Superpermutation Problem, and it stands unsolved for $n > 5$ as of now.

The answer to the problem was conjectured to be the following value by D. Ashlock and J. Tillotson: $$\sum_{i = 1}^n i!$$ The conjecture has been verified for $n \leqslant 5$, but it was later proven wrong for $n \geqslant 6$. The value of the above sum for $n = 6$ is $873$, but Robin Houston provided a counterexample, which was a superpermutation of length $872$, one less than the conjectured length, to disprove the conjecture. This paper explains the problem and the conjecture, and proof that the conjecture is wrong, in detail.

Quoting from the paper:
The minimal length is still unknown for $n ≥ 6$, but we can show that for all $n ≥ 6$ it is strictly less than the conjectured length $\sum_{i = 1}^n i!$

In the contest, what people have done for this problem is, they have printed the conjectured length for $n \leqslant 5$, and one less than the conjectured length for $n > 5$. However, "strictly less than" the conjectured length does not mean one less than the conjectured length.

So I request @admin to do something about it. Probably remove the problem and its submissions from CodeChef, if possible.

Viewing all 40121 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>