一开始觉得思路问题不大就是WA,打了个球回来又看了会,可能是自己默认测试数据全为正数了,改了下判断的逻辑就ac了
1 #include <iostream> 2 #include <cstdio> 3 #include <vector> 4 #include <algorithm> 5 6 using namespace std; 7 8 int matrix[15][105]; 9 int d[15][105]; 10 int m, n; 11 int nextr[15][105]; 12 13 int main() 14 { 15 16 while (cin >> m >> n) 17 { 18 for (int i = 0;i < m;i++) 19 for (int j = 0;j < n;j++) 20 cin >> matrix[i][j]; 21 //最后一列边界情况 22 for (int i = 0;i < m;i++) 23 d[i][n - 1] = matrix[i][n - 1]; 24 25 for(int c=n-2;c>=0;c--) 26 for (int r = 0;r < m;r++) 27 { 28 d[r][c] = matrix[r][c]; 29 int a[3] = { r - 1,r,r + 1 }; 30 if (r == 0)a[0] = m - 1; 31 if (r == m - 1)a[2] = 0; 32 sort(a, a + 3); 33 int minval = (1 << 30);//这道题测试数据有负数-- 34 for (int k = 0;k < 3;k++) 35 { 36 if (minval>d[a[k]][c + 1]) 37 { 38 minval = d[a[k]][c + 1]; 39 nextr[r][c] = a[k]; 40 } 41 } 42 d[r][c] += minval; 43 } 44 45 int ans = (1 << 30); 46 int maxr; 47 for (int i = 0;i < m;i++) 48 if (ans > d[i][0]) 49 { 50 ans = d[i][0]; 51 maxr = i; 52 } 53 cout << maxr + 1; 54 for (int i = nextr[maxr][0], j = 0;j < n - 1;i = nextr[i][j]) 55 { 56 cout << " " << i + 1; 57 ++j; 58 } 59 60 cout << " " << ans << endl; 61 } 62 63 return 0; 64 }