16ms 解法:
#include <cstdio> //using namespace std; int data[7][7]; int dp[7][7]; int row_min[7]; int row_max[7]; int n,min,max; void solve(int row) { int i,j,pos,tmp, tmp_max; if (row == n) { max = dp[n-1][0]; for (i = 0; i < n; i++) { if (max < dp[n-1][i]) { max = dp[n-1][i]; } } if (min > max) { min = max; } return; } //prune, the above max value + current line min value > current answer min, then return if (row_max[row-1]+row_min[row]>min) { return; } for(i = 0; i < n; i++) { //tmp_max cal current row's dp max value tmp_max = -999999; for (j = 0; j < n; j++) { tmp = i+j; pos = tmp < n ? tmp : tmp-n; dp[row][pos] = dp[row-1][pos] + data[row][j]; if (dp[row][pos] > tmp_max) { tmp_max = dp[row][pos]; } } row_max[row] = tmp_max; solve(row+1); } } int main() { int i,j,val,mymin,mymax; while(scanf("%d", &n) && n != -1) { for (i = 0; i < n; i++) { mymin = 999999; for (j = 0; j < n; j++) { scanf("%d", &val); data[i][j] = val; if (val < mymin) { mymin = val; } } row_min[i] = mymin; //cal min value for every row } mymax = -999999; for (i = 0; i < n; i++) { dp[0][i] = data[0][i]; if (data[0][i] > mymax) { mymax = data[0][i]; } } row_max[0] = mymax; //first row's max value min = 9999999; solve(1); printf("%d ", min); } return 0; }