日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

UVA - 11882Biggest Number dfs+期望剪枝

發布時間:2024/4/11 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 UVA - 11882Biggest Number dfs+期望剪枝 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題意:在一個R行C列(2=<R,C<=15,R*C<=30)的矩陣里有障礙物和數字格(包含1~9的數字)。你可以從任意一個數字格出發,每次沿上下左右的方向走一格,但不能走障礙格中,也不能重復經過,然后把沿途經過的所有數字連起來,問能得到的最大整數是多少?

分析:題目很簡單,但容易超時,必須加上預期剪枝,就是當前搜索的和它之后可能搜索的最大長度加起來是否超過當前最優解,如果相等就按字典序比較,否則回溯。

# include<iostream> # include<cstdio> # include<cmath> # include<map> # include<queue> # include<string> # include<string.h> #include<set> #include<list> # include<algorithm> using namespace std; char mp[30][30]; int row, col; int vis[30][30]; int dx[] = { 1,-1,0,0 }; int dy[] = { 0,0,1,-1 }; pair<int, int>que[100]; int head, tail; int viss[30][30]; string res; int h(int x,int y) {head=tail = 0;int cnt = 0;que[tail++] = make_pair(x, y);memcpy(viss, vis, sizeof(viss));while (head < tail) {pair<int, int>u = que[head++];for (int i = 0; i < 4; i++) {int ddx = u.first + dx[i];int ddy = u.second + dy[i];if (ddx < 0 || ddx >= row || ddy < 0 || ddy >= col)continue;if (!viss[ddx][ddy]&&mp[ddx][ddy]!='#') {viss[ddx][ddy] = 1;cnt++;//還能搜索的長度que[tail++] = make_pair(ddx, ddy);}}}return cnt; } void dfs(int curx,int cury,int layer,string A) {int ant = h(curx, cury);int l = res.size();if (layer + ant < l)return;//期望剪枝if (layer + ant == l) {if (A + "z" < res)return;//字典序剪枝}if (A.size() > res.size() || (A.size() == res.size() && res < A))res = A;//更新結果for (int i = 0; i < 4; i++) {int ddx = curx + dx[i];int ddy = cury + dy[i];if (ddx < 0 || ddx >= row || ddy < 0 || ddy >= col)continue;if (vis[ddx][ddy]||mp[ddx][ddy]=='#')continue;vis[ddx][ddy] = 1;dfs(ddx, ddy, layer + 1, A+mp[ddx][ddy]);vis[ddx][ddy] = 0;}} int main() {while (cin >> row >> col && row&&col) {for (int i = 0; i < row; i++)cin >> mp[i];memset(vis, 0, sizeof(vis));res = "";for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {if (mp[i][j]!='#') {string A="";A+=mp[i][j];vis[i][j] = 1;dfs(i, j, 1, A);vis[i][j] = 0;}}}cout << res << endl;}return 0; }

?

總結

以上是生活随笔為你收集整理的UVA - 11882Biggest Number dfs+期望剪枝的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。