We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Counting On a Tree
Counting On a Tree
Sort by
recency
|
9 Discussions
|
Please Login in order to post a comment
here is hackerrank couting on a tree solution
Hi there!
Don't use stupid
main
function provided by Hackerrank forJava
.It is extremly slow! Just load of test case exceed time limit on test case 4+.
Beware! Rewrite it:
Tough one. DFS for depth building, LCA for path finding (using depth), trying to put node with most connections at the root of the tree, simple math for sums (will fit in normal int), optimized visited nodes storage. Tried caching paths (no improvement). Still getting 8 timeouts (TCs: 5,6,8,9,11,14,15,17) :(
Undoubtedly there's another algo or structure I need to use.
include
include
include
include
include
include
using namespace std;
typedef struct _node { _node * prev; int value; int index; _node() { prev = NULL; value = 0; index = 0; } } NODE;
int GetPathFromRoot(int b, NODE *pNode, vector& nodes) { unsigned int i = 0; NODE *curNode = &pNode[b]; do { nodes.push_back(curNode); curNode = curNode->prev; } while (curNode != NULL); return 0; } int num = 0; int GetPath(int a, int b, NODE *pNode, vector& nodes) { //Get root to a vector rootA; vector rootB;
}
int FindSame(int w, int x, int y, int z, NODE *pNode) { int nMatch = 0; vector wxNode; vector yzNode; GetPath(w, x, pNode, wxNode); GetPath(y, z, pNode, yzNode);
for (unsigned int i = 0; i < wxNode.size(); i++) { for (unsigned int u = 0; u < yzNode.size(); u++) { if (wxNode[i]->value == yzNode[u]->value && (wxNode[i] != yzNode[u])) { nMatch++; } } } cout << nMatch << endl; return nMatch; }
int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */
int nodeNum = 0; int queryNum = 0; int i = 0; cin >> nodeNum; num = nodeNum; cin >> queryNum; NODE *pNode = new NODE[nodeNum];
}
workts but timeout
Can this be passed with Python? I implemented a min-heap, and used it for dijkstra pathfinding, and I still timeout on all tests but the first.