whenever i use dfs or bfs following my template I get tle for example
this question-
https://mirror.codeforces.com/contest/1600/problem/J
this is my submission-
https://mirror.codeforces.com/contest/1600/submission/135985780
№ | Пользователь | Рейтинг |
---|---|---|
1 | jiangly | 3977 |
2 | tourist | 3815 |
3 | jqdai0815 | 3682 |
4 | ksun48 | 3614 |
5 | orzdevinwang | 3526 |
6 | ecnerwala | 3514 |
7 | Benq | 3483 |
8 | hos.lyric | 3381 |
9 | gamegame | 3374 |
10 | heuristica | 3358 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 169 |
2 | -is-this-fft- | 162 |
3 | Um_nik | 161 |
4 | atcoder_official | 159 |
5 | djm03178 | 157 |
5 | Dominater069 | 157 |
7 | adamant | 154 |
8 | awoo | 152 |
8 | luogu_official | 152 |
10 | TheScrasse | 148 |
whenever i use dfs or bfs following my template I get tle for example
this question-
https://mirror.codeforces.com/contest/1600/problem/J
this is my submission-
https://mirror.codeforces.com/contest/1600/submission/135985780
Название |
---|
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).
so when u pass that huge array into your function it takes O(size of array) to pass it — no it doesn't
Check the following accepted Java 11 solution using
InputStreamReader
,BufferedReader
andBufferedOutputStream
classes.136061200
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)+" ");
without.print(arr.get(i)+" ");
. Thep
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
andCharacter
. 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 foradj
andch
. 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 thedfs
.