taiPyのお悩み解決ブログ

日々の発見をまとめます!

Javaの解答例:学習記録:B - Foreign Exchange , トヨタ自動車プログラミングコンテスト2024#2(AtCoder Beginner Contest 341)

はじめに

トヨタ自動車プログラミングコンテスト2024#2(AtCoder Beginner Contest 341)のB - Foreign Exchange という問題の学習記録です。Javaで書いています。

メモ

この問題のポイント

  • 例から考えること
  • 手を動かして考えること
  • Long型を使うこと。intで書いていた部分を全部longに変えるとAC(要するに正解)しました!

目次

問題と解説

問題

atcoder.jp

解説

www.youtube.com

YouTube解説

atcoder.jp

解答例

ステップ

  • インプットを格納する
  • 1つ目の国から取れるだけお金を交換する
  • これを最後までする。

はい、以上!

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        long[] a = new long[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        long[] s = new long[n - 1];
        long[] t = new long[n - 1];

        for (int i = 0; i < n - 1; i++) {
            s[i] = sc.nextInt();
            t[i] = sc.nextInt();
        }

        for (int i = 0; i < n - 1; i++) {
            long temp = a[i];
            // System.out.println(temp);

            long order = s[i];
            // System.out.println(order);
            
            long quotient = temp / order;

            a[i + 1] += quotient * t[i];
            // System.out.println(a[i + 1]);
        }

        System.out.println(a[n - 1]);

        sc.close();
    }
}

公式の回答をJavaに!

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long n = scanner.nextLong();
        long[] a = new long[200001];
        long[] s = new long[200001];
        long[] t = new long[200001];

        for(int i = 1; i <= n; i++) a[i] = scanner.nextLong();
        for(int i = 1; i <= n-1; i++) {
            s[i] = scanner.nextLong();
            t[i] = scanner.nextLong();
        }

        for(int i = 1; i <= n-1; i++) a[i+1] += a[i]/s[i] * t[i];
        System.out.println(a[(int)n]);
    }
}

短く1行で収まりますね!