Zzyzx's blog

By Zzyzx, 6 years ago, In English,

I just recently came across the GregorianCalendar class in Java. http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html

I tried to see if it works well by using it for this practice problem -> http://codeforces.com/contest/304/problem/B

After writing the code, I tested the two given sample cases on my computer and it gives the right output. Nice! Ctrl+A -> Ctrl+C -> Ctrl+V -> Submit! But to my utter dismay, "Wrong Answer on pretest 1". I am dumbfounded and have no idea why this is happening.

Here are my (almost identical) submissions: http://codeforces.com/contest/304/submission/4106624 -> WA on pretest 1 (Why!?) http://codeforces.com/contest/304/submission/4106538 -> WA on pretest 2 (Why!?) http://codeforces.com/contest/304/submission/4107237 -> Accepted (How is this different!?)

Can anybody explain why this is so?

  • Vote: I like it
  • 0
  • Vote: I do not like it

6 years ago, # |
  Vote: I like it +6 Vote: I do not like it

You initialized GregorianCalendar with default locale and time zone, but Codeforces uses time zone with 23- or 25-hour days at some dates due to daylight savings. Because of that, your difference in milliseconds sometimes gets minus one hour becoming minus one after integer divisions.

Your accepted solution, in contrast to others, uses rounding, thus unintentionally leading to correct answer. As for your first submission, it uses default constructor, which initializes GregorianCalendar with current date and time. When you set year, month and day, GregorianCalendar tries to adjust time of the day in some complicated way according to time zone, resulting in one more hour lost between 1900:01:01 and 2038:12:31. This doesn't happen in your second submission, because it doesn't use default constructor.

  • »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    So the safest option for the above mentioned kind of questions would be to just write our own functions to calculate the difference in time, is it?