Stuck in HOLI spoj problem


Giving WA

Hey,i couldn’t understand your logic completely.Also,i would say that your code is quite complex than what is actually needed.You can see my code.It is accepted.

  1. #include

  2. #include

  3. #include

  • using namespace std;

  • const int N = 100 * 1000 + 10;

  • vector g[N], w[N];

  1. bool u[N];

  2. int cnt[N];

  3. int n;

  4. long long res;

  • void dfs(int v)
  1. {

  2. u[v] = true;

  3. for (int i = 0; i < g[v].size(); i++)

  4. {

  5. int to = g[v][i];

  6. if (u[to])

  7. continue;

  8. dfs(to);

  9. res += min(cnt[to], n - cnt[to]) * 2ll * w[v][i];

  10. cnt[v] += cnt[to];

  11. }

  12. }

  • void solve(int test)
  1. {

  2. scanf("%d", &n);

  3. for (int i = 0; i < n; i++)

  4. {

  5. g[i].clear();

  6. w[i].clear();

  7. u[i] = false;

  8. cnt[i] = 1;

  9. }

  10. for (int i = 0; i < n - 1; i++)

  11. {

  12. int x, y, z;

  13. scanf("%d%d%d", &x, &y, &z);

  14. –x;

  15. –y;

  16. g[x].push_back(y);

  17. g[y].push_back(x);

  18. w[x].push_back(z);

  19. w[y].push_back(z);

  20. }

  21. res = 0;

  22. dfs(0);

  23. printf("Case #%d: ", test);

  24. printf("%lld\n", res);

  25. }

  • int main()
  1. {

  2. int t;

  3. scanf("%d", &t);

  4. for (int i = 1; i <= t; i++)

  5. solve(i);

  • return 0;
  1. }

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.