Ali Test Written Exam Questions-Bricklaying Problem


Code:

Idea: Calculate the number of gaps in each vertical column to get the maximum value. Add 1 to the place where there is a gap, you can get the number of gaps in 5 columns from 0 to 4, and store it in num[].

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main2 {

	/** 请完成下面这个函数,实现题目要求的功能 **/
	/** 当然,你也可以不按照这个模板来作答,完全按照自己的想法来 ^-^ **/
	static int leastBricks(List<List<Integer>> wall) {
		int n = wall.get(0).size();
		int sum = 0;
		for (int i = 0; i < n; i++) {
			sum += wall.get(0).get(i);
		}
		int[] num = new int[sum - 1];
		for (int j = 0; j < wall.size(); j++) {
			int temp = 0;
			for (int i = 0; i < wall.get(j).size() - 1; i++) {
				temp += wall.get(j).get(i);
				num[temp - 1] += 1;
			}
		}
		int result = Integer.MIN_VALUE;
		for (int i = 0; i < sum - 1; i++) {
			if (num[i] > result)
				result = num[i];
		}
		return wall.size() - result;
	}

	public static void main(String[] args) {
		List<List<Integer>> vecvecRes = new ArrayList<List<Integer>>();
		List<Integer> list = new ArrayList<Integer>();
		Scanner in = new Scanner(System.in);
		int res = -1;

		int row = 0;

		row = Integer.parseInt(in.nextLine().trim());
		int i = 0;
		while (i < row) {

			int a = Integer.parseInt(in.nextLine().trim());
			if (a == 0) {
				vecvecRes.add(list);
				list = new ArrayList<Integer>();
				i++;
			} else {
				list.add(a);
			}

		}
		res = leastBricks(vecvecRes);

		System.out.print(res);

	}
}


Guess you like

Origin blog.csdn.net/m0_37541228/article/details/77598252