jovial3's blog

By jovial3, history, 2 years ago, In English

whenever i use dfs or bfs following my template I get tle for example

this question-

https://codeforces.com/contest/1600/problem/J

this is my submission-

https://codeforces.com/contest/1600/submission/135985780

  • Vote: I like it
  • +3
  • Vote: I do not like it

| Write comment?
»
2 years ago, # |
  Vote: I like it -50 Vote: I do not like it

a) use not java, its slow b) (the actual reason) everything in java is pass-by-value, so when u pass that huge array into your function it takes O(size of array) to pass it, so its not actaually O(1000000).

  • »
    »
    2 years ago, # ^ |
      Vote: I like it +9 Vote: I do not like it

    so when u pass that huge array into your function it takes O(size of array) to pass it — no it doesn't

»
2 years ago, # |
Rev. 10   Vote: I like it 0 Vote: I do not like it

Check the following accepted Java 11 solution using InputStreamReader, BufferedReader and BufferedOutputStream classes.

136061200

»
2 years ago, # |
  Vote: I like it +4 Vote: I do not like it

Well, your solution has correct complexity, but, unfortunately, the program needs constant-time optimizations. I made a few changes to it and got accepted: 136101196.

The first thing to do was to replace p(arr.get(i)+" "); with out.print(arr.get(i)+" ");. The p function always flushes the output and flush is very slow. You don't need to flush the output unless the problem is interactive, probably only at the very end of the program. However, getting rid of flush wasn't sufficient.

Then I turned to other thing, that you also should want to avoid as much as possible in competitive programming: wrapper classes like Integer and Character. They are created on the heap and much slower than primitive types (that are kept on the stack). It was a little bit more brain-involving, but I set constant lengths for adj and ch. I replaced absent values with some neutral elements (like -1 or '\0') to show, that actually there is no value.

The mixture of the two optimizations made the program to pass. If it haven't, I probably would got rid of the 'adj' matrix at all and look, if the bit is set in a[i][j] or not, right in the dfs.