洛谷 P1464 Function Java

dfs,记忆化搜索

import java.util.*;
class Main{
    static int[][][] f = new int[25][25][25];//使用f数组来进行记忆化搜索
    public static int w(int a,int b,int c){
        if(a<=0 || b<=0 || c<=0) {
            return 1;
        }else if(a>20 || b>20 || c>20) {
            return w(20,20,20);
        }else if(f[a][b][c]!=0) {//记忆化搜索
            return f[a][b][c]; //如果之前被计算过,那么直接返回存在数组中的结果;没有计算过的,就进行的计算
        }else if(a<b && b<c) {
            f[a][b][c] = w(a,b,c-1)+w(a,b-1,c-1)-w(a,b-1,c);
        }else {
            f[a][b][c] = w(a-1,b,c)+w(a-1,b-1,c)+w(a-1,b,c-1)-w(a-1,b-1,c-1);
        }
        return f[a][b][c];
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int a , b , c;
        a = sc.nextInt();
        b = sc.nextInt();
        c = sc.nextInt();
        while(true){
            if (a==-1 && b==-1 && c==-1)    break;
            System.out.println("w("+a+", "+b+", "+c+") = "+w(a,b,c));
            a = sc.nextInt();
            b = sc.nextInt();
            c = sc.nextInt();
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_45260619/article/details/105526838