fork download
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class Main implements Runnable {
  5. public static void main(String[] args) {
  6. new Thread(null, new Main(), "", 256 * (1L << 20)).start();
  7. }
  8.  
  9. @Override
  10. public void run() {
  11. int n = 500000;
  12. List<Integer>[] g = new List[n];
  13. for (int i = 0; i < n; i++) {
  14. g[i] = new ArrayList<>();
  15. }
  16. for (int i = 1; i < n; i++) {
  17. int p = i - 1;
  18. g[i].add(p);
  19. g[p].add(i);
  20. }
  21.  
  22. long t1 = System.nanoTime();
  23. int result = dfs(0, -1, g);
  24. long t2 = System.nanoTime();
  25. System.out.println("time = " + (t2 - t1) / 1.0e9 + " sec, result = " + result);
  26. }
  27.  
  28. private int dfs(int x, int p, List<Integer>[] g) {
  29. int result = 1;
  30. for (int y : g[x]) {
  31. if (y == p) {
  32. continue;
  33. }
  34. result += dfs(y, x, g);
  35. }
  36. return result;
  37. }
  38. }
Success #stdin #stdout 4.98s 216924KB
stdin
Standard input is empty
stdout
time = 4.819740287 sec, result = 500000