Official

B - 入金と出金 / Income and Expenses Editorial by cn449


入金額の合計と出金額の合計を表す変数をそれぞれ用意し、\(0\) で初期化します。

for 文や if 文などを用いて、\(i = 1, 2, \ldots, N - 1\) に対して \(i\) 件目の取引が入金と出金のどちらであるか判定し、合計の金額に足し合わせればよいです。

実装例

#include <iostream>
#include <vector>

using namespace std;

int main() {
	int n;
	cin >> n;
	vector<int> a(n);
	for (int i = 0; i < n; i++) cin >> a[i];
	int x = 0, y = 0;
	for (int i = 0; i < n - 1; i++) {
		if (a[i] < a[i + 1]) x += a[i + 1] - a[i];
		else y += a[i] - a[i + 1];
	}
	cout << x << ' ' << y << '\n';
}

posted:
last update: