AOJ 0008 Sum of 4 Integers

リンク AOJ 0008 Sum of 4 Integers

方針

愚直にforの4重ループで全探索しています。この手の問題はforループで書いてしまうと、Time Limit(今回は1sec)に間に合わないことが多いです。
今回は、O(n^4)の計算量に対して、n = 50なので、50^4 = 6250000となり、まず大丈夫です。

ソース

import java.util.*;
public class Main {
    static Scanner sc = new Scanner(System.in);
    static int number;
    public static void main(String[] args){
        while(read()){
            slove();
        }
    }
    static boolean read(){
        if(!sc.hasNextInt())return false;
        number = sc.nextInt();
        return true;
    }
    static void slove(){
        int a, b, c, d, count;
        count = 0;
        for(a = 0; a < 10; a++){
            for(b = 0; b < 10; b++){
                for(c = 0; c < 10; c++){
                    for(d = 0; d < 10; d++){
                        if(a+b+c+d == number){
                            count++;
                        }
                    }
                }
            }
        }
        System.out.println(count);
    }
}