LoginSignup
0
0

More than 1 year has passed since last update.

【AIZU ONLINE JUDGE】ITP1_4_D 最大値, 最小値, 合計値

Posted at

はじめに

アルゴリズムの勉強として、AIZU ONLINE JUDGEの問題を解いている。
最大値, 最小値問題のメモリのサイズを小さくするコツを備忘録として残しておく。

問題

n個の整数 ai(i=1,2,...n)を入力し、それらの最小値、最大値、合計値を求めるプログラムを作成してください。

Input

1行目に整数の数nが与えられます。2行目にn個の整数aiが空白区切りで与えられます。

Output

最小値、最大値、合計値を空白区切りで1行に出力してください。

Constraints

0<n≤10000
−1000000≤ai≤1000000

Sample Input

5
10 1 5 4 17

Sample Output

1 17 37

実装比較

Constraintsを参考にすることで、最小値を100000, 最大値を-100000に初期値で渡すことができる。
これによって、indexが0のとき、代入処理を書く必要がなく、コードの記述量を抑えることができる。

初期値を代入する場合

sample
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int max, min;
    long long total = 0;
    
    for (int i=0; i<n; i++) {
        int a;
        cin >> a;
        if (i==0) {
            max = a;
            min = a;
        }
        if (i!=0 && max<a) {
            max = a;
        }
        if (i!=0 && min>a) {
            min = a;
        }
        total += a;
    }
    
    cout << min << " " << max << " " << total << endl;
}

入力範囲の最大, 最小を代入する場合

sample
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int min = 1000000;
    int max = -1000000;
    long long total = 0;
    
    for (int i=0; i<n; i++) {
        int a;
        cin >> a;

       if (max < a) {
         max = a;
       }

       if (a < min) {
         min = a;
       }
       total += a;
    }
    
    cout << min << " " << max << " " << total << endl;
}

おわりに

まだまだ、アルゴリズムの勉強が足りないので、今後も継続して行っていく

参考リンク

ITP1_4_D: Min, Max and Sum - AIZU ONLINE JUDGE
人はなぜ、long long を使うのか? (競技プログラミング)

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0