[Java] Number Triangles

/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: lincans1
LANG: JAVA
TASK: numtri
*/
import java.io.*;
import java.util.*;

public class numtri {
    
    

	public numtri() throws IOException {
    
    
		// Use BufferedReader rather than RandomAccessFile; it's much faster
		BufferedReader f = new BufferedReader(new FileReader("numtri.in"));
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("numtri.out")));

		int R = Integer.parseInt(f.readLine());
		int[][] mat = new int[R][R];
		for (int i = 0; i < R; i++) {
    
    
			StringTokenizer st = new StringTokenizer(f.readLine());
			for (int j = 0; j <= i; j++) {
    
    
				mat[i][j] = Integer.parseInt(st.nextToken());
			}
		}
		for (int i = 1; i < R; i++) {
    
    
			mat[i][0] += mat[i-1][0];
			for (int j = 1; j <= i; j++) {
    
    
				mat[i][j] += Math.max(mat[i-1][j-1], mat[i-1][j]);
			}
		}
		int max = 0;
		for (int j = 0; j < R; j++) {
    
    
			max = Math.max(max, mat[R - 1][j]);
		}
		out.println(max);
	    out.close();                                  // close the output file
	    f.close();
	}
	
	public static void main (String [] args) throws IOException {
    
    
		new numtri();
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41714373/article/details/112427628