sicily 1158. Pick numbers bfs
2011-04-15 18:29
435 查看
//这题一开始感觉是dp,状态转移方程为dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + maze[i][j] //提交上去WA //后来发现这题不能用dp,因为题目要求的是正的最小值,状态转移方程的min会取到负数, //当求出dp [m]为负数时,有可能存在一条和为正的路径 //注意到n,m都比较小,可以直接用bfs搜索过 #include <iostream> #include <queue> using namespace std; const int N = 15; const int INF = 1000000000; int maze ; int n, m; int ans; int dx[] = {1, 0}; int dy[] = {0, 1}; struct status { int row,col,sum; status() {} status (int row, int col, int sum) { this->row = row; this->col = col; this->sum = sum; } }; void bfs() { queue<status> Q; Q.push(status(1, 1, maze[1][1])); status p,tmp; while (!Q.empty()) { p = Q.front(); Q.pop(); if (p.row == n && p.col == m && p.sum > 0) ans = min(p.sum, ans); for (int i = 0; i < 2; i++) { tmp = p; tmp.row += dx[i]; tmp.col += dy[i]; if (tmp.row >= 1 && tmp.row <= n && tmp.col >= 1 && tmp.col <= m) { tmp.sum += maze[tmp.row][tmp.col]; Q.push(tmp); } } } } int main() { while (cin >> n >> m) { for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> maze[i][j]; ans = INF; bfs(); if (ans < INF) cout << ans << endl; else cout << -1 << endl; } return 0; }
相关文章推荐
- Sicily 2369. Nim-B Sum
- Sicily 4835. Numbersrebmun
- Sicily 1176 Two Ends
- Sicily 1153 马的周游问题[Special judge] && sicily 1152
- Sicily 2376. Cutting The Cake
- Sicily 2609/1954. Bracket Expression
- Sicily 1950. Brain Teasers
- Sicily 1907. Collision Detection
- Sicily 1829/1948. Largest Area
- Sicily 1219. 新红黑树
- Sicily 1718. University Rankings
- Sicily 13296. Kingdom Rush II
- Sicily 2391. Tri graphs
- Sicily 1053. Peg Game
- Sicily 1078. Beer Land
- Sicily 2302. Queue Implementation Using a Circular
- Sicily 1729. Steganography
- Sicily 1350. Piggy banks
- Sicily 1351. Multi-key Sorting
- Sicily 1839. Stone Game