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

CNTDIGIT - Editorial

$
0
0

Problem Link:contest, practice

Difficulty: Medium-Hard

Pre-requisites: DP

Problem:

Given an integer N. You are to calculate the sum of distinct digits that appear in the decimal representation of at least one of the numbers L, L+1 ... R for each pair (L, R), where 1 ≤ LRN.

Explanation:

The first observation is that all ranges that contain 10 or more integers will have the answer 10. So, we can calculate the answer for them separately. Otherwise, the answer will be between 1 and 10 and the size of the range will be less than 10. The most hard part of the problem is to handle that kind of ranges.

I strongly recommend you to read the following editorials before this one and understand it: Round Numbers (USACO), FAVNUM (CodeChef). Otherwise, it's gonna be super-hard to understand this editorial.

Let's make an array B[], which contains the digits of N(from the most to the least significant bits). For example, if N = 1240941, then B[] = [1, 2, 4, 0, 9, 4, 1]. After that, we should precaculate the following dynamic programming: F( the size of the prefix of B )( boolean flag, that indicates if the current prefix is equal to the corresponding one in B )( bitmask of different digits, that we have faced so far ). F equals to the number of different prefixes with the corresponding properties. If you understand the editorials, that I have suggested above, then you should be able to calculate that DP in O( 2 * 210 len( N ) ) time.

OK, now let's discuss the hardest part.

Let's represent L(the left bound of some range) like "....x9999..999y", where x and y are digits. More than this, x is not greater than 8. Now we are working only with ranges that contain less than 10 elements, so the part of L, which lays before x, will stay the same for any possible R. Also, let's fix D = R - L(0 ≤ D≤ 8). Then, we can easily say, how does the part of R, that corresponds to the "x9999..999y" part of L after adding D, look like. To calculate the answer for all variants with fixed x, the number of 9's after x, y and D we can use the precaculated DP F. It's kind of meet-in-the-middle approach: the first half of the numbers we treat with DP, the second half of the numbers has a pattern "x9999..999y" and it's also fixed.

You should be really careful to consider all the possible cases and calculate the answer correctly. I suggest you to think about the solution for a while. If you still don't understand the conception - feel free to ask a question.

Please, check out Setter's and Tester's solutions for your better understanding.

Total complexity is O( 2 * 210 len( N ) + 9 * 10 * len( N ) * 8 * len( N ) ).

Setter's Solution:link

Tester's Solution:link


shooting: corner test case

Why august cookoff had no cakewalk question?

$
0
0

The setting guidelines says that there should be 1 cakewalk (direct approach) question in cook off. But this time all questions were bit harder than previous cook-offs. why is it so?

[Suggestion] testing page for testing different cases.

$
0
0

At the time of contests, it would be great if we can test our test cases against the working code, that would give a better understanding of the problem.

Sometime it is too confusing by just considering the sample test case or if some test case is correct as per our code, so if we can test custom test cases against the correct code, so that we can be sure about our approach and would be easier to debug.

for this there can be a different page (linked to every problem) where user will only be able to get the output by giving input, other than input and output nothing else will be provided.

TREERGB - Editorial

$
0
0

Problem Link:contest, practice

Difficulty: Easy-Medium

Pre-requisites: DP on Trees

Problem:

Given a rooted tree with N vertices. You would like to paint each vertex of the tree in one of three possible colors: red, green, and blue. The following conditions must be fulfilled: for each vertex painted red, there must be no more than R red vertices in its subtree; for each vertex painted green, there must be no more than G green vertices in its subtree; for each vertex painted blue, there must be no more than B blue vertices in its subtree.

Find the number of ways to paint the tree modulo 1000000007.

Explanation:

First of all, I strongly recommend you to read the following article about calculating knapsack problem on a tree(link; check out Chapter 7.3). Otherwise, it's gonna be super-hard to understand this editorial.

This is original Author's explanation(corrected and edited by me). It's quite tricky and there's no implementation details, but the main idea is described. If you need details - feel free to ask them in the comments.

After that, if we have some vertex V painted in some color, and this vertex is OK, than we don't care about vertices of the same color in the subtree of V.

Then we should handle two DP functions. Let's assume, that the root is painted in red color(it can be blue or green as well, but we'll consider the only case; the others are similar).

The first DP looks like this: F(V)(cntRed). In this DP we ensure, that the number of red vertices in the subtree of V is OK. So, we'll iterate though all the children of vertex V and will choose whether to paint them in red or in some other color. Let's fix some child U. If we choose red color, then we call F, otherwise, we call G( G(V)(cntGreen) if we paint the child blue, and G(V)(cntBlue) if we paint the child green(not vice-versa) ).

G looks like this: G(V)(cntGreen) or G(V)(cntBlue). I will describe the first one. In this DP, we ensure that all green vertices are OK. Also note that when we call this DP from F, we know that the root(of our subtree) is painted blue. This means that we don't need to care about all blue vertices in the subtree, only about the root (so only the number of blue vertices is interesting for us). But we have to keep the number of green vertices as the state of the DP. So we actually forget about the red color in G.

Now, when we made a call of G from F, we have some cntGreen vertices painted green, and Size(v) - cntGreen vertices that we painted blue (we actually brute force cntGreen). But, we can paint some of the blue vertices in red color. So, we also brute this number, and use some Cnk to find the number of ways to repaint some blue vertices in red color. Note, that we have to ensure that the number of blue vertices in the subtree of the child is also OK.

Total complexity is O( N3 ), O( N2 ) for calculing G and O( N3 ) for calculing F.

Please, check out Setter's and Tester's solutions for your better understanding.

Setter's Solution:link

Tester's Solution:link

Problems with Java

How to calculate memory required by a c Program ?

$
0
0

Is there any way we will find the time and memory required by a c program ?

TREEGAME - Editorial

$
0
0

Problem Link:contest, practice

Difficulty: Easy

Pre-requisites: Greedy, Games

Problem:

Given a rooted tree. Two players play a game on the tree. The first player can delete arbitrary non-empty set of roots during his turn, the second player can delete arbitrary non-empty set of leaves during his turn. The game ends when the tree becomes empty. The first player wants the game to end as soon as possible, while the second player wants the game to run as long as possible. Both players play optimally. You are to determine the number of moves of the game.

Explanation:

In problems like this it's always required to come up with some insights like "It's always optimal to play like this..." or "It's possible to win making only that kind of operations..." and so on.

The first greedy insight for solving this problem is the following: the first player should always delete all available roots at the moment.

Why? Because he wants to end up this game as soon as possible! Not deleting all available roots may lead the game to be longer.

The second player always delete the deepest leaf in the current tree.

So, we should just simulate the game according to the winning strategy of both players. Let's focus on some implementation details.

First of all, we can sort all the vertices by its depth. Then we can maintain pointer L on the last vertex deleted by the first player. Also, we can maintain pointers R on the last vertex deleted by the first player.

When it's the first player's move, then we should delete all vertices that have the same depth with L's vertex in sorted order.

When it's the second player's move, then we should delete R's vertex in sorted order.

Total complexity is O( N log N ) per testcase.

Please, check out Setter's and Tester's solutions for your better understanding.

Setter's Solution:link

Tester's Solution:link


PERMSUFF - Editorial

$
0
0

Problem Link:contest, practice

Difficulty: Simple

Pre-requisites: Sorting, Scanline

Problem:

Given a permutation P of N integers. Also, given M ranges (Li, Ri). You are allowed to perform the next procedure a finite number of times: choose any given range (L, R) and shuffle subsegment P[L..R] arbitrarily. You are to determine if it's possible to obtain P out of the 1, 2, ..., N permutation.

Explanation:

At first, let's assume, that all the ranges don't intersect(it means, that for any two given ranges A = (L1, R1) and B = (L2, R2) there's no integer K, that simultaneously belongs to A and B). If that's not true, than we can unite some of the ranges with a help of scanline algorithm(check out Setter's and Tester's solutions if you are not familiar with that algorithm).

So, all the ranges don't intersect. Then the solution is pretty easy: the answer is "Possible" if and only if i and Pi belong to the same range for each i.

It's may be not clear why it's OK to unite some ranges. But it's not hard to prove the correctness of this approach: we can construct permutation P element-by-element, starting with putting P1 on the first place and so on. We can perform the putting stage of the algorithm with some greedy approach.

Total complexity is O( N log N ) per testcase.

Please, check out Setter's and Tester's solutions for your better understanding.

Setter's Solution:link

Tester's Solution:link

PERMSUFF august cookoff 2014

$
0
0

why is my submission not accepted....

include <iostream>

include <cstdio>

include <vector>

define s(a) scanf("%lld" , &a)

define pp printf("Possible\n")

define pi printf("Impossible\n")

using namespace std;

int main() {

long long int t, n, m, i,j, c = 1, l, r , f = 0,k ,min = 1000000, f2 = 0;
s(t);

while(t--) {        
    s(n);
    s(m);

    vector <long long int> a(n+1,0);
    vector <long long int> b(n+1,0);

    for (i = 1; i <= n; i++) {
        s(k);
        a[i] = k;
    }

    for (i = 1; i <= m; i++) {
        s(l);
        s(r);

            for (j = l; j <= r; j++) {
                if((b[j] < min) && (b[j] > 0)) {
                    min = b[j];     
                }

                if(b[j] > 0) {
                    f2 = 1;
                }
            }

            if (f2 == 1) {
                for (j = l; j <= r; j++) {
                    b[j] = min;
                }
            } else {
                for (j = l; j <= r; j++) {
                    b[j] = c;
                }
                c++;
            }
    }

    for (i = 1; i <= n; i++) {
        if(b[a[i]] != b[i]) {
            f = 1;
        }
    }

    if(f == 1) {
        pi;
    } else {
        pp;
    }

    f2 = 0;
    f = 0;      
    c = 1;
    min = 10000000;
}

return 0;

}

SHOOTING - Editorial

$
0
0

Problem Link:contest, practice

Difficulty: Simple

Pre-requisites: Bruteforce, Greedy

Problem:

Given a rectangular grid with N rows and M columns. Each its cell is either empty, contains an enemy, or contains a laser. Each laser can shoot in one of three directions: either left, right or up. When a laser shoots at some direction, it kills all the enemies on its way. There're L lasers on the grid.

You are to determine whether it's possible to kill all the enemies on the grid.

Explanation:

The key observations are that there're at most 16 lasers on the grid and there're only 3 directions to shoot.

So, let's just choose those lasers, who will shoot in the up direction(let's call them "vertical" lasers, those who are not chosen are "horizontal") There're at most 216 variants, so we can simply iterate through them. After that, we can solve the problem independently for each row. How?

If there're no alive enimies left on a row(after the "vertical" lasers shot), then it's OK. Otherwise, if there're no "horizontal" laser in the row, then the current variant fails. If there're one "horizontal" laser on the row, then we should check if all the enemies lies to the one side of the laser. If there're one "horizontal" laser on the row, then it's OK anyway(we can make the most left one shoot to the right, the most right one shoot to the left - so all the row will be covered).

Total complexity is O( 2L NM ) per testcase.

Please, check out Setter's and Tester's solutions for your better understanding.

Setter's Solution:link

Tester's Solution:link

SHOOTING - COOK49 WA

$
0
0

I used naive recursion because the constraints were small. My code is: So x1, y1 indicates the position upto which we have checked the lasers. The function will copy the grid to a1,a2 and a3. In a1, I killed all enemies in upper direction and recursively called the function again. In a2, I killed all the ones in left direction, and in a3, I killed the ones in right direction. Can someone please help! It sucks that I am getting WA.

#include<iostream>
#include<vector>
#include<string>
using namespace std;

bool proc(int x1,int y1,vector<string> a,int n,int m);

int main()
{
    int t;
    cin >> t;
    while(t--)
    {
              int n,m;
              cin >> n >> m;
              vector<string> a;
              a.resize(n);
              for(int i = 0;i < n;i++)
                              cin >> a[i];
              bool c = proc(0,0,a,n,m);
              if(c == true) cout << "Possible" << endl;
              else cout << "Impossible" << endl;
    }
    return 0;
}

bool proc(int x1, int y1,vector<string> a,int n,int m) {
     int x,y;
     for(x = x1;x < n;x++)
             for(y = y1;y < m;y++)
                   if(a[x][y] == 'L') goto label1;
     if(x == n || y == m)
     {
          for(int i  = 0;i < n;i++)
                  for(int j = 0;j < m;j++)
                          if(a[i][j] == 'E') return false;
          return true;
     }
     label1: ;
     vector<string> a1;
     vector<string> a2;
     vector<string> a3;
     a1.resize(n);
     a2.resize(n);
     a3.resize(n);
     for(int i = 0;i < n;i++)
                      a1[i] = a[i];
     for(int i = 0;i < n;i++)
                      a2[i] = a[i];
     for(int i = 0;i < n;i++)
                      a3[i] = a[i];

     for(int i = x;i >= 0;i--)
             if(a1[i][y] == 'E') a1[i][y] = '.';
     a1[x][y] = '.';
     bool l = proc(x,y,a1,n,m);
     if(l == true) return true;

     for(int i = y;i >= 0;i--)
             if(a2[x][i] == 'E') a2[x][i] = '.';
     a2[x][y] = '.';
     bool k = proc(x,y,a2,n,m);
     if(k == true) return true;

     for(int i = y;i < m;i++)
             if(a3[x][i] == 'E') a3[x][i] = '.';
     a3[x][y] = '.';
     bool d = proc(x,y,a3,n,m);
     if(d == true) return true;

     return false;
}

cryptography

$
0
0

hai frands am going to do a new encryption method who are intersted in cryptography they acan join with me (renjithsraj@live.com), i need ideas about encryption and decryption techniques

Graph Adjacency List Representation in C

$
0
0

Any Body have Short and Simple Graph Adjacency List Representation code in C.

TRANSFORM THE EXPRESSION wrong answer

$
0
0

My algorithm

  • Start from the left
  • if it encounters an operator checks the what is to the right of the operator
  • if at the right it finds an operand shifts the operator to the right
  • if the program finds a bracket to the right it shifts the operator to wherever the bracket closes
  • else it leaves the operator wherever it is I know the stack method but i wanted to implement my own method, and i'm getting right answers for whatever test cases i've entered on my own and also the sample test cases Here's my code

include <stdio.h>

include <string.h>

char postfix[405];

int isOperator(char s) { if((s=='+')|| (s=='-')||(s=='/')||(s=='*')||(s=='^')) { return 1; } else{ return 0; } } int isOperand(char s){ if(!isOperator(s) && s!='(' && s!= ')') { return 1; } else{ return 0;

}} int WhereShift(char s[],int i){ int open=0,j=0; if(isOperand(s[i+1])&&s[i+1]!='\0') { //printf("%d",i); return i+1; } else if(/isOperand(s[i-1]) &&/ s[i+1]==40) { open=1; for(j=i+2;open>0;j++) { if(s[j]==41) open--; if(s[j]==40) open++; } return j-1; } /else if(s[i-1]==41 && s[i+1]==40) { open=1; for(j=i+2;open>0;j++) { if(s[j]==41) open--; if(s[j]==40) open++; } return j-1; }/ else { return i; } } void shift(char *s, int i, int j) { char temp = s[i]; int k; for(k=i;k<j;k++){ s[k]=s[k+1]; } s[j]=temp; //printf("%c%d",temp,j); //printf("%c",s[j]);

} void removeBrackets(char *s){ int i; int k=0; for(i=0;i<strlen(s);i++){ if(s[i]!=41 && s[i]!=40){ postfix[k++]=s[i]; } }

}

int main() { char s[405]; int t,i,j; scanf("%d",&t); for(j=0;j<t;j++){ scanf("%s",s); for(i=0;i<strlen(s);i++){ if(isOperator(s[i])){ //printf("%d",WhereShift(s,i)); shift(s,i,WhereShift(s,i)); //printf("%s\n",s);

        }
    }
    removeBrackets(s);
    //printf("%s",s);
    printf("%s\n",postfix);
    //printf("%c\n",s[strlen(s)-1]);

}
    return 0;  
    }

am i a fibonacci number

Algorithm Development

$
0
0

Can one become excellent competitive programmer in 2 years if one do his best...

How did mugurelionut & ACRush became so great at competitive programming?

$
0
0

I just wonder how these both great programmers became so great at programming. How did they started programming, and what makes them so unique.

I see,they write 200-300 lines of codes for challenge problem to get that 1 point. And in all contests they finish in top 5. For me it's just like OMG :O

And how old are both of them?(and how much experience)

runtime error found in input taking (as i debugged)

$
0
0

while(t--) { string s,s2; cin>>n>>m; z=n*m; while(n--) { cin>>s2; cout<<n<<" "; s.append(s2); }


-----

-----


}

My doubt is that why is runtime error coming for 18 and 24 but not for 3*3.Actually the string is not taking input properly.Am i not aware of any string property?

SPOJ question IITKWPCI wrong answer

$
0
0

I am getting WA in this question -> http://www.spoj.com/problems/IITKWPCI/

Here is my solution -> http://ideone.com/mJsLSq

My algorithm creates an undirected graph having n vertices and positions i,j which are 'good' are connected with an edge. Then it finds connected components in this graph, sort data on the positions in each component separately and print out the resulting array. It would be helpful if anyone can give a case on which this algorithm fails, because I have tried many corner cases myself. Thanks in advance :)

PS: I have assumed we can do multiple swaps between same pair of good positions. For example, if 1,2 is a good position pair, we can swap data at positions 1 and 2 multiple times. Please tell if this assumption is incorrect as well.

Viewing all 39796 articles
Browse latest View live


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