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

Getting wrong answer in GCDQ

$
0
0

I am getting wrong answer in GCDQ. I know that my algorithm can lead to Time Limit Exceeded but I want to know that why it is not getting accepted even for some points (any idea for some specific test cases)? My ouput is correct.

The link to my code is: https://ideone.com/70eNrH


Doubt in the CLPERM question of the ongoing Jan 15 long contest?

$
0
0

I just wish to know will the game be played if the value of K=0 as no numbers fell the mother wont be sad so the game should not be played right? :p

QSET - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Lalit Kundu
Tester:Shiplu Hawlader
Editorialist:Lalit Kundu

DIFFICULTY:

MEDIUM

PRE-REQUISITES:

Segment Trees, Number Theory

PROBLEM:

Given a string of digits of length N<(105), do two kind of operations(total of M<(105):

  • Type 1: 1 X Y: Replace AX by Y.
  • Type 2: 2 C D: Print the number of sub-strings divisible by 3 of the string denoted by AC, AC+1 ... AD.
    Formally, you have to print the number of pairs (i,j) such that the string Ai, Ai+1 ... Aj, (C ≤ i ≤ j ≤ D), when considered as a decimal number, is divisible by 3.

QUICK EXPLANATION:

Use segment trees. Store in node for each interval,
- the answer for that interval
- count1[], where count1[i] denotes number of prefixes of interval which modulo 3 give i.
- count2[], where count2[i] denotes number of suffixes of interval which modulo 3 give i.
- total, sum of interval modulo 3.

Perform merge operations in constant time.

EXPLANATION:

We basically need to find number of subarrays in range L to R who sum is divisible by 3.
Queries are for ranges, where we have to count subarrays, we can use segment tree because we can solve our problem if we can merge two intervals and find answer for the new interval in constant time.
We can use segment tree because we can take two different subarrays and merge them in constant time to find answer for the new large subarray.
In segment tree, each subarray's information is recursively calculated from two smaller subarrays.
While querying, we can merge different(and disjoint) subarrays to get answer for range L to R.
So, we need to design the node of our segment tree. We store in our node, the answer for current subarray. Also, we will store two arrays count1[] and count2[] as defined above.
While merging two intervals(say node1 and node2), our new answer will be node1.answer + node2.answer, plus count of valid subarrays which start in node1 and end in node2.

image

This pseudo code will clear the things.

//merges node1 and node2 and stores in node3
merge(node1, node2, node3)
    //non intersecting subarrays of node1 and node2
    node3.ans = node1.ans + node2.ans
    for i = 0 to 2:
        for j = 0 to 2:
            //if adding suffix of node1 with modulo i
            //to prefix of node2 with modulo j
            //gives us a subarray divisible by 3
            if (i + j) % 3 == 0:
                //all pairs of valid indexes are valid subarrays
                node3.ans += node1.count2[i] * node2.count1[j]

Note now, we also need to build both array count1 and count2 for the new interval.
Let's build count1 first:
Say there were count1[i] prefixes of node2 which when taken modulo with 3 gave i. Now, all such prefixes will give (i + node1.total) % 3, where node1.total denotes total sum of interval modulo 3. So, we can calculate new arrays. In similar way, we can calculate count2.

image

//building count1 and count2
for i=0 to 2:
    node3.count1[i] = node1.count1[i] + node2.count1[3-node1.total+i]
    node3.count2[i] = node2.count2[i] + node1.count2[3-node2.total+i]

So, complexity is: O(N log N) preprocessing and O(log N) per query.

ALTERNATIVE SOLUTION:

Suppose we keep in segment tree for each node, how many prefix sums in this interval are divisible by 0,1,2.
For a query [L,R], we just have to count number of prefix sums in interval [L,R] divisible by 0,1,2(let's call them s1,s2,s3).
Our answer will be s1*s1+s2*s2+s3*s3.
Why? Because, suppose prefix_sum[i] % 3 = prefix_sum[j] % 3, then sum of substring [i+1, j] is divisible by 3.

For update query(mark A[x] = y), since we are keeping prefix sum modulo 3, for range [x, N], we increase/decrease each prefix sum by k(k<3). We can do this using lazy propagation.

SOLUTIONS:

Setter's solution
Tester's solution

Getting wrong answer in SEAVOTE

$
0
0

I am getting wrong answer in SEAVOTE. I know that my algorithm can lead to Time Limit Exceeded but I want to know that why it is not getting accepted even for some points (any idea for some specific test cases)? My output is correct.

The link to my code is: https://ideone.com/Z1qEIB

ONEKING - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Snigdha Chanda
Tester:Shiplu Hawlader
Editorialist:Lalit Kundu

DIFFICULTY:

EASY-MEDIUM

PRE-REQUISITES:

Greedy

PROBLEM:

Given N (≤100000) intervals [Ai, Bi], one such interval can be deleted by placing a bomb at x if Ai≤ x ≤ Bi. Find minimum number of bombs required to delete all intervals.

EXPLANATION:

First we sort all intervals according to increasing Bi.
Now, let's say we have placed a bomb at position x on the line. All intervals such that their starting point Ai≤ x will get destroyed. So we'll greedily place the bombs when required.

Pseudo code:

n,a,b = input
ar=[]    //ar[i] denotes maximum starting point for intervals ending at i

for i=1 to N:
    ar[b[i]]=max(ar[b[i]], a[i])

ans=0
max=-1  //denotes the latest value of x where we placed a bomb

for i=0 to 2000:
    //we need a bomb to all intervals ending at i'th position
    if max < ar[i]:
        ans += 1
        max = i
print ans

Complexity: O(N+2000).

SOLUTIONS:

Setter's solution
Tester's solution

RANKA - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Gaoyuan Chen
Tester:Shiplu Hawlader
Editorialist:Lalit Kundu

DIFFICULTY:

MEDIUM-HARD

PRE-REQUISITES:

Ad-hoc, Graph theory, Games

PROBLEM:

Given a empty board of 9x9, each of the two players(black and white) move alternately. In each move, the player must put the stone on an empty cell or pass the turn. If this player put a stone, following situation will happen.
-> If after this move there is at least one connected component of opponent dead, then stones from these dead components will be removed. (In this case, after remove all dead components of your opponent, we can prove all your connected component are not dead.)
->Otherwise, if there are at least one connected component of yours dead, then this move is invalid.

In order to avoid infinite loops, there is a rule called "No same state". The state of board can be expressed as a string with length 82:
the first character indicate who is the next player, then 9*9 character indicate the state of a certain cell. If after one move the game goes into a state that previously occurred, then this move is invalid.
Player can also use to "pass" their move(ie. no change in state).
You are given an integer N. Please output a match that contains N valid moves for both player.

EXPLANATION:

There can be many solutions to this problem. You can think of various game plays where connected components get deleted(while making sure the state remains unique). One or two of them, I'll explain here.

->I request users to explain their approach if it's unique/different. It surely will help others.

APPROACH 1:

1. The Gadget: Ko

We will use the following gadget to build our answer: image
It has the following feature: the left state can transform into the right state by place a white stone, and the right state can transform back into the left state by place a black stone.

This structure in Go is called Ko: http://en.wikipedia.org/wiki/Ko_fight

2. How to use Gadget

We can place lots of this kind of gadget on the board, for example, this configuration has 8:
image
So one state can be represented by an 8 bits number: 0 to 255. We want to go through these 256 numbers, the adjacent ones should have at most 1 bit different. How to do that? We can use Gray code: http://en.wikipedia.org/wiki/Gray_code
So we can make about 256 * 1.5 steps now. (if we place want to place 2 black(white) stone in a row, we must pass one turn, so on average it needs 1.5 moves for one number).

3. Use the remaining cells

After each 256 * 1.5 steps, we can modify the remaining board a bit, then make another 256 * 1.5 steps and so on. We can just fill in one cells each time: the cells that marked with a red circles.
image
Now we can generate answer for about 256 * 1.5 * 30 moves, that is enough.

APPROACH2:

The basic thinking behind this approach was behind the fact that if player1 passes each time and player2 fills up the whole board(cell by cell) except one cell, player1 can now, place in the empty cell and remove all pegs of player2.
In such a way, players can keep leaving one cell empty(different cell each time). So, we can generate a total of 81*81*2(note the passes).
Note all states generated are unique.

So, following moves will be generated:

player1 fills whole board except (1,1) (meanwhile player2 passes)
player2 puts at (1,1) (all pegs of player1 get removed)
player2 fills whole board except (1,2) (meanwhile player1 passes)
player1 puts at (1,2) (all pegs of player2 get removed)
player1 fills whole board except (1,3) (meanwhile player2 passes)
player2 puts at (1,3) (all pegs of player1 get removed)
.
.
.
and so on for 81 cells.

APPROACH3:

Use some strategy to search for an answer directly: http://www.codechef.com/viewsolution/5731906

SOLUTIONS:

Setter's solution
Tester's solution

What language??

$
0
0

Well i want to become a software engineer and i learned some C . been working on problems for quite a while but i don't know where should i go to c++ or Java or continue with C. Any help like giving me ideas or what should i do?

Sereja and Number Division 2 scores getting down ?

$
0
0

The scores from the my submissions tab are same( around 84 ) but when I see the ranking for January Challenge the score shown for the problem is very low( about 13-14 ).. And the submissions who have directly printed the input string are getting above 50. What is going on ?


CLPERM - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Sunny Aggarwal
Tester:Shiplu Hawlader
Editorialist:Lalit Kundu

DIFFICULTY:

MEDIUM

PRE-REQUISITES:

Maths

PROBLEM:

K numbers denoted by array B from set S = [1,2,...N] are removed. Find the minimum number X such that X cannot be formed by picking a set of numbers from S.
1 ≤ N≤ 109
1 ≤ K ≤ 5*105

EXPLANATION:

If the minimum X is odd, second player wins, else first player wins.
So, we just need to find X.

If k == 0, then all numbers from 1 to (N * (N + 1)) / 2 are possible to form.
Consider a special case, X = 1 if 1 has been removed from set [1..N].

Based on this observation, we can first sort the array B in ascending order.
Fact: Let's say all numbers from 1 to i are available, then we can form every number till (i * (i + 1)) / 2.

Let's consider last reachable number till now is M. So now we want to form numbers M + 1, M + 2 and so on.
We have generated all numbers till M now and now we want to generate M + 1 and the new number that available number we get is say Bi + 1, we can't generate M + 1, if Bi + 1 > M + 1. In such a case X will be M + 1.
Or else, we know that all numbers between Bi + 1 and Bi+1 - 1(both inclusive) are available. So, we know that all numbers from M + 1 to M + S are also available, where S = sum of all numbers between Bi + 1 and Bi+1 - 1(both inclusive).

We do this for all unavailable numbers in sorted traversal to get the maximum unachievable sum M.

Complexity: O(K log K)

You might want to read this, for better clarity.

SOLUTIONS:

Setter's solution
Tester's solution

Codechef CHRL2

$
0
0

Codechef Lunchtime 08 Question CHRL2 http://www.codechef.com/problems/CHRL2

Editorial suggests a DP solution in O(n^2)

I was thinking of a different solution. Obviously , I got a WA. But I can't figure out the mistake can anyone help ?

Suppose we store all the occurrences of C,H,E,F seperately.

Then we match each C to the first H which comes after it and then with first E that comes after H and first F that comes after E. And proceed accordingly.

for eg. in CHHHEEEFFCC vc -> 0, 9, 10 vh -> 1,2,3 ve -> 4,5,6 vf -> 7,8

now vc[0] = 0; we can match it with 1(i.e H), 4, and 7 Now vc[1] = 9 There is no i such that vh > 9 Therefore program ends.

Can anyone point out the mistake ?

~Thanks

Unofficial Easy editorial for SEAVOTE(JAN15 long challenge) for beginnners

$
0
0

SEAVOTE: after observing the question,

            B1-1<A1<=B1
            B2-1<A2<=B2
            B3-1<A3<=B3
            ........
            ........
            Bn-1<An<=Bn
            n=>Total number of elements.
            Summing(As we do in 10th standard :) :)  )
            I think there is no need of writting pseudo-code for sum=B1+B2+...+Bn :)
            sum-n<100(given)<=sum
            -n<100-sum<=0
            This condition is equivalent to ( 100+n>sum) && (sum>=100) ............(1)
            Now=>so called PITFALL for this question :(
            Bi can be zero But Ai can't be negative :) (e.g. A1=-0.01 not possible.)
            therefore don't include elements having zero value.
            Elements having zero value will not be resposible for n.
            I mean if B is=>{34,34,0,0,34} Then n=3 and sum=102.
            APPLY EQUATION (1), YOU WILL GET THE ANSWER.
            I think this much explanation is CRYSTAL CLEAR!!

            MY SOLUTION=>http://www.codechef.com/viewsolution/5699787

C vs C++ for XRQRS

TopCoder SRM 645 editorial

when would the rank be updated??

$
0
0

when the updated ranking of the jan 15 long will come up?

Optimizations for SEAND2 (january challenge 14)

$
0
0

Anyone please explain SEAND2's solution used by the toppers. Time constraint Simulated Annealing fetched me around 74% . I am wondering what the toppers have used ? I know they have many 2D tables tables and their own random permutation generators in their solutions, but don't have any idea of their approaches.

I guess my simulated annealing solution was not perfect but i would like to know other peoples approaches.

thanks


Paying Up ! Find the error

$
0
0

I am unable to get why my algo fails in the last sample test case of the problem Here is my code :

#include<cstdio>
#include<algorithm>

using namespace std ;

int main ()
{
    int m , i , t , n , arr[22] , j   ; 
    scanf ("%d",&t) ; 
    while (t--)
    {
        scanf ("%d %d",&n , &m) ; 
        for (i = 0 ; i<n ; i ++)
            scanf ("%d",&arr[i]) ; 
        sort (arr , arr+n )  ;

        printf ("AFter Sorting Output of the array\n")  ; 
        for (j = 0 ;  j<n ; j++)
            printf ("arr[%d] = %d\n",j,arr[j])  ;

        for (i = n ; i>=0 ; i--)
        {
            if (arr[i] <= m)
            {
                m = m - arr[i] ; 
                if (m == 0 )
                    break ; 
            }
        }

        if (m == 0 ) 
            printf ("Yes\n")  ; 
        else 
            printf ("No\n")  ; 
    } 
return 0 ; 
}

If there is some mistake in this algo please sugggest me some other algo ..THANKS A LOT !!!

XOR queries

Help Me to solve this dp problem.

Data Structures and Algorithms

$
0
0

Hi all, I need your help to make a list of most used data structures and algorithms along with their tutorials, implementation and some problems on them. It will be helpful to everyone in many ways. I request everyone to contribute to this list by providing links to tutorials, problems, etc. I will keep updating this list regularly.

  1. Binary Search : Tutorial, Problems, Tutorial, Implementation, Problem

  2. Quicksort : Tutorial, Implementation, Tutorial

  3. Merge Sort : Tutorial, Implementation, Tutorial

  4. Suffix Array : Tutorial, Tutorial, Implementation, Tutorial, Implementation, Problem, Problem

  5. Knuth-Morris-Pratt Algorithm (KMP) : Tutorial, Tutorial, Implementation, Tutorial, Problem

  6. Rabin-Karp Algorithm : Tutorial, Implementation, Tutorial, Problem, Problem

  7. Tries : Tutorial, Problems, Tutorial : I,II, Tutorial, Problem, Problem, Problem

  8. Depth First Traversal of a graph : Tutorial, Impelementation, Tutorial, Problems, Problem, Problem, Problem

  9. Breadth First Traversal of a graph : Tutorial, Impelementation, Tutorial, Problems, Problem, Problem, Problem, Flood Fill

  10. Dijkstra's Algorithm : Tutorial, Problems, Problem, Tutorial(greedy), Tutorial (with heap), Implementation, Problem, Problem

  11. Binary Indexed Tree : Tutorial, Problems, Tutorial, Original Paper, Tutorial, Tutorial, Problem, Problem, Problem, Problem, Problem, Problem, Problem

  12. Segment Tree (with lazy propagation) : Tutorial, Implementation, Tutorial, Tutorial, Problems, Implementation, Tutorial, Implementation and Various Uses, Persistent Segment Tree, problems same as BIT, Problem, Problem/HLD is used as well/

  13. Z algorithm : Tutorial, Problem, Tutorial, problems same as KMP.

  14. Floyd Warshall Algorithm : Tutorial, Implementation, Problem, Problem

  15. Sparse Table(RMQ) : Tutorial, Problems, Tutorial, Implementation(C++), Java implementation

  16. Heap / Priority Queue / Heapsort : Implementation, Explanation, Tutorial, Implementation, Problem, Chapter from CLRS

  17. Modular Multiplicative Inverse

  18. nCr % M

  19. Suffix Automaton : Detailed Paper, Tutorial, Implementation (I), Tutorial, Implementation (II), Problem, Problem, Problem, Problem, Tutorial, Implementation

  20. Lowest Common Ancestor : Tutorial, Problems, Paper, Paper, Problem, Problem, Problem

  21. Counting Inversions : Divide and Conquer, Segment Tree, Fenwick Tree, Problem

  22. Euclid's Extended Algorithm

  23. Suffix Tree : Tutorial, Tutorial, Intro, Construction : I, II, Implementation, Implementation, Problem, Problem, Problem, Problem

  24. Dynamic Programming : Chapter from CLRS(essential), Tutorial, Problems, Problem, Problem, Problem, Problem, Tutorial, Problem, Problem, Problem, Longest Increasing Subsequence, Bitmask DP, Bitmask DP, Optimization, Problem, Problem, Problem, Problem, Problem, Problem, Problem, DP on Trees : I, II

  25. Basic Data Structures : Tutorial, Stack Implementation, Queue Implementation, Tutorial, Linked List Implementation

  26. Logarithmic Exponentiation

  27. Graphs : Definition, Representation, Definition, Representation, Problem, Problem

  28. Minimum Spanning Tree : Tutorial, Tutorial, Kruskal's Implementation, Prim's Implementation, Problem, Problem, Problem, Problem, Problem

  29. Efficient Prime Factorization

  30. Combinatorics : Tutorial, Problems, Problem, Tutorial

  31. Union Find/Disjoint Set : Tutorial, Tutorial, Problems, Problem, Problem, Problem

  32. Knapsack problem : Solution, Implementation

  33. Aho-Corasick String Matching Algorithm : Tutorial, Implementation, Problem, Problem, Problem, Problem

  34. Strongly Connected Components : Tutorial, Implementation, Tutorial, Problem, Problem, Problem

  35. Bellman Ford algorithm : Tutorial, Implementation, Tutorial, Implementation, Problem, Problem

  36. Heavy-light Decomposition : Tutorial, Problems, Tutorial, Implementation, Tutorial, Implementation, Implementation, Problem, Problem, Problem

  37. Convex Hull : Tutorial, Jarvis Algorithm Implementation, Tutorial with Graham scan, Tutorial, Implementation, Problem, Problem, Problem, Problem, Problem

  38. Line Intersection : Tutorial, Implementation, Tutorial, Problems

  39. Sieve of Erastothenes

  40. Interval Tree : Tutorial, Implementation, Problem, Problem, Problem, Problem, Problem, Problem, Tutorial

  41. Counting Sort

  42. Probabilities

  43. Matrix Exponentiation : Tutorial, Tutorial

  44. Network flow : (Max Flow)Tutorial : I,II, Max Flow(Ford-Fulkerson) Tutorial, Implementation, (Min Cut) Tutorial, Implementation, (Min Cost Flow)Tutorial : I,II,III, Dinic's Algorithm with Implementation, Max flow by Edmonds Karp with Implementation, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem

  45. K-d tree : Tutorial, Tutorial, Implementation, Problem

  46. Deque

  47. Binary Search Tree : Tutorial, Implementation, Searching and Insertion, Deletion

  48. Quick Select : Implementation, Implementation

  49. Treap/Cartesian Tree : Tutorial(detailed), Tutorial, Implementation, Uses and Problems, Problem, Problem

  50. Game Theory : Detailed Paper, Tutorial, Problems, Grundy Numbers, Tutorial with example problems - I,II,III,IV, Tutorial, Problems, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Nim

  51. STL (C++) : I,II, Crash Course

  52. Maximum Bipartite Matching

  53. Manacher's Algorithm : Implementation, Tutorial, Tutorial, Implementation, Tutorial, Implementation, Problem, Problem, Problem

  54. Miller-Rabin Primality Test : Code

  55. Stable Marriage Problem

  56. Hungarian Algorithm, Tutorial

  57. Sweep line Algorithm : I, II

  58. LCP : Tutorial, Implementation, Tutorial, Implementation

  59. Gaussian Elimination

  60. Pollard Rho Integer Factorization, problem

  61. Topological Sorting

  62. Detecting Cycles in a Graph : Directed - I, II Undirected : I

  63. Geometry : Basics, Tutorial

  64. Backtracking : N queens problem, Tug of War, Sudoku

  65. Eulerian and Hamiltonian Paths : Tutorial, Tutorial, (Eulerian Path and Cycle)Implementation, (Hamiltonian Cycle)Implementation

  66. Graph Coloring : Tutorial, Implementation

  67. Meet in the Middle : Tutorial, Implementation

  68. Arbitrary Precision Integer(BigInt), II

  69. Radix Sort, Bucket Sort

  70. Johnson's Algorithm : Tutorial, Tutorial, Implementation

  71. Maximal Matching in a General Graph : Blossom/Edmond's Algorithm, Implementation, Tutte Matrix, Problem

  72. Recursion : I,II, Towers of Hanoi with explanation

  73. Inclusion and Exclusion Principle : I, II

  74. Co-ordinate Compression

  75. Sqrt-Decomposition : Tutorial, Tutorial, Problem, Problem

  76. Link-Cut Tree : Tutorial, Wiki, Tutorial, Implementation, Problem, Problem, Problem, Problem

  77. Euler's Totient Function : Explanation, Implementation, Problems, Explanation, Problems

  78. Burnside Lemma : Tutorial, Tutorial, Problem

  79. Edit/Levenshtein Distance : Tutorial, Introduction, Tutorial, Problem, Problem

  80. Branch and Bound

  81. Math for Competitive Programming

How to reduce TLE beyond recursive approach?

$
0
0

I am trying to program a problem that asks to compute answer in form of two functions of the form: answer=A ( B (arg1,arg2)) I have used recursive approach to implement A and B. But it shows TLE despite simple standard recursive definitions.

Viewing all 39796 articles
Browse latest View live


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