algorithm - Hacker rank Similar Pairs -
i trying solve hacker rank similar pairs https://www.hackerrank.com/contests/101hack/challenges/similarpair problem. cant figure out why failing large test cases. using segment trees solve problem in nlogn time. can find code below.
#include<iostream> #include<vector> using namespace std; vector<int> graph[110001]; int t, st[100001*4] = {0}, n, deg[100001] = {0}; void update(int node, int b, int e, int idx, int val) { if(b > node || e < node) return; if(b == e) { st[idx] += val; return; } update(node, b, (b + e)/2, 2 * idx, val); update(node, (b + e)/2 + 1, e, 2 * idx + 1, val); st[idx] = st[2 * idx] + st[2 * idx + 1]; } long query(int l, int r, int b, int e, int idx) { if( l > e || r < b) return 0; if(l <= b && r >= e) return st[idx]; return query(l, r, b, (b + e)/2, 2 * idx) + query(l, r, (b + e)/2 + 1, e, 2 * idx + 1); } long long similarpairs(int node) { int l = max(1, node - t), r = min(n, node + t); long res = 0; res = query(l, r, 1, n, 1); update(node, 1, n, 1, 1); for(int = 0; < graph[node].size(); i++) { res += similarpairs(graph[node][i]); } update(node, 1, n, 1, -1); return res; } int main() { long x, y, root, result, start; cin >> n >> t; for(int = 0; < n - 1; i++) { cin >> x >> y; graph[x].push_back(y); deg[y]++; } for(int = 1; <= n; i++) if(!deg[i]) root = i; result = similarpairs(root); cout << result << endl; cin.get(); return 0; }
i doing. problem missing long long
s. long
same int
(on 32 bits), must use long long
everywhere, since result not fit in 32 bit int.
this gets ac:
#include<iostream> #include<vector> using namespace std; vector<int> graph[110001]; int t, n, deg[100001] = {0}; long long st[100001*4] = {0}; void update(int node, int b, int e, int idx, int val) { if(b > node || e < node) return; if(b == e) { st[idx] += val; return; } int m = (b + e) >> 1; int q = idx << 1; update(node, b, m, q, val); update(node, m + 1, e, q + 1, val); st[idx] = st[q] + st[q+1]; } long long query(int l, int r, int b, int e, int idx) { if( l > e || r < b) return 0; if(l <= b && r >= e) return st[idx]; int m = (b + e) >> 1; int q = idx << 1; return query(l, r, b, m, q) + query(l, r, m + 1, e, q + 1); } long long similarpairs(int node) { int l = max(1, node - t), r = min(n, node + t); long long res = 0; res = query(l, r, 1, n, 1); update(node, 1, n, 1, 1); for(int = 0; < graph[node].size(); i++) { res += similarpairs(graph[node][i]); } update(node, 1, n, 1, -1); return res; } int main() { long x, y, root, start; cin >> n >> t; for(int = 0; < n - 1; i++) { cin >> x >> y; graph[x].push_back(y); deg[y]++; } for(int = 1; <= n; i++) if(!deg[i]) root = i; long long result = similarpairs(root); cout << result << endl; cin.get(); return 0; }
Comments
Post a Comment