Блог пользователя jovial3

Автор jovial3, история, 2 года назад, По-английски

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

  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
2 года назад, # |
  Проголосовать: нравится -50 Проголосовать: не нравится

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 года назад, # ^ |
      Проголосовать: нравится +9 Проголосовать: не нравится

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

»
2 года назад, # |
Rev. 10   Проголосовать: нравится 0 Проголосовать: не нравится

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

136061200

»
2 года назад, # |
  Проголосовать: нравится +4 Проголосовать: не нравится

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.