WHY TLE ?

Правка en2, от fakeac, 2017-02-02 22:21:29

I have written the code to solve this problem, but it gives TLE. I think the complexity of my soln. is O(n). My approach is as follows:

Let dp[from][to] =1 if all nodes in the subtree of "to" (including "to") are of the same color when we perform dfs from node "from" and "to" is the child of node "from". dp[from][to] = 0, otherwise.

To calculate dp[from][to] we use dfs. Let node "to" have k children, then let's compute dp[to][child] for all children of "to". Then dp[from][to]==1 if and only if dp[to][child]==1 for all children of "to" and the color[child]==color[to] for all children of "to". Otherwise, dp[from][to]=0;

Now, to compute the final answer, Let's iterate over all "from" nodes, and for each "to" such that "to" is adjacent to "from", if dp[from][to]==1, then final answer="YES", and node="from".

If no such "from" is found then answer="NO";

But this looks like O(n^2) solution. But, if we observe carefully, we see that each "from","to" pair of nodes corresponds to a directed edge going from node "from" to node "to". Since there are exactly n-1 edges, the no. of "from","to" pairs = 2*(n-1).

Here is my submission ----> http://codeforces.me/contest/764/submission/24382711. 
NOTE: In this solution instead of passing -> "from","to" to dfs function, I have passed "from","index of 'to' in adj[from]". I have made multiple dfs calls but each call is computed exactly once, since I have made a vis[] array which keeps track of it.
Please tell where I am wrong in calculating the time complexity?
Thanks in advance.
Теги trees, dp, dfs and similar, #implementation

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en5 Английский fakeac 2017-02-02 23:32:10 261
en4 Английский fakeac 2017-02-02 22:26:10 6
en3 Английский fakeac 2017-02-02 22:23:16 91
en2 Английский fakeac 2017-02-02 22:21:29 39
en1 Английский fakeac 2017-02-02 22:20:17 1668 Initial revision (published)