猫でもわかるWebプログラミングと副業

本業エンジニアリングマネージャー。副業Webエンジニア。Web開発のヒントや、副業、日常生活のことを書きます。

AOJ 2639: Yamanote Line

はじめに

方針

  • ひたすらぐるぐる回るのをシミュレーション
  • 起きた時間, 寝た時間 をそれぞれ60で割った余りを start, end とする
  • その間に停車時間cが入っていればいい。
    • start < end の場合は start <= c かつ c <= end となってればいい
    • start > end の場合は c <= start または end <= c となっていればいい
  • 最終的な停車時間は頑張って求める
  • 一生降りられないということをどう判断するか?
    • visited[] 配列を使った。1週60分のうち、過去と同じタイミングで目が覚めた場合、あとはループするので降りられない。

実装

class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(new InputStreamReader(System.in));
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        boolean[] visited = new boolean[60];
        int time = 0;
        
        while(!visited[time % 60]) {
            visited[time % 60] = true;
            int start = time % 60;
            time += a;
            int end = time % 60;
            // dは最終的な答えを求めるのに使う
            int d = (time % 60 - c + 60) % 60;
            if(start < end){
                if(start <= c && c <= end) {
                    System.out.println(time - d);
                    return;
                }
            }else{
                if(c <= end || start <= c) {
                    System.out.println(time - d);
                    return;
                }
            }
            time += b;
        }
        System.out.println(-1);
    }
}