[HDU] 2612 Find a way - 用单源最短论经模拟的简单广搜
題目鏈接:
http://acm.hdu.edu.cn/showproblem.php?pid=2612
方法:其實就是從兩個點分別探尋單源最短路徑,兩個點到同一個目標位置的最短路徑都求出來,相加,然后找出到哪一個相同目標位置的最短路徑之和最小即可,采用的模擬dijsktral算法。
要注意的一個地方是,找到一個kfc后一定還要繼續(xù)去找,而不是向其他廣搜題那樣就停止探尋了,不能有思維定勢啊。
實現(xiàn)方法為,初始的時候?qū)蓚€源點到目標位置的距離設(shè)置為正無窮,然后分別用單元最短路徑的算法模擬廣搜并更新到目標位置的距離,最后在目標位置中找到最短路徑之和最小的,由于正無窮和任何數(shù)之和都是正無窮,所以如果遇到不是被兩個源點都可以達目標位置時,起路徑和為正無窮,在比較的時候都會被忽略掉。
除此之外,記錄目標位置坐標的數(shù)組不能開在200內(nèi),這里要細心,這里最多可以用接近4萬個。
感想:思維定勢造成一個下面如此簡單的測試數(shù)據(jù)拜掉,wa了很久。
3 5
??????????????????? Y...@
??????????????????? ####@
??????????????????? M....
代碼:
View Code #include <iostream> #include <queue> #include<algorithm> using namespace std; int n,m; char map[202][202]; int dY[202][202]; int dM[202][202]; const char wall='#'; const char road='.'; const char Y='Y'; const char M='M'; const char KFC='@'; const int MAX=0x7fffffff; int YposX,YposY,MposX,MposY; bool v[202][202]; int deriction[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; struct Step {int x,y;int currentUsedTime; }; void BFSSearch(char who) { memset(v,false,sizeof(v));int x = who == Y ? YposX:MposX;int y = who == Y ? YposY:MposY;Step step;step.x = x;step.y = y;step.currentUsedTime = 0;queue<Step> q;q.push(step);while(!q.empty()){Step t_step = q.front();q.pop();if(!v[t_step.x][t_step.y]){v[t_step.x][t_step.y]= true;if(map[t_step.x][t_step.y]==KFC){if(who == Y && dY[t_step.x][t_step.y]>t_step.currentUsedTime)dY[t_step.x][t_step.y]=t_step.currentUsedTime;if(who == M && dM[t_step.x][t_step.y]>t_step.currentUsedTime)dM[t_step.x][t_step.y]=t_step.currentUsedTime;}//下面的部分不能放在與上面對應(yīng)的else里面,找一個kfc還要繼續(xù)找,//這樣才符合dijsktral算法的特點。//不要受一般廣搜的思維定勢限制。//否則下面測試數(shù)據(jù)肯定要敗掉/*3 5Y...@####@M....*/int n_x,n_y;Step n_step;for(int i =0;i<4;i++){n_x = t_step.x+deriction[i][0];n_y = t_step.y+deriction[i][1];if(map[n_x][n_y]!=wall && !v[n_x][n_y]){n_step.x=n_x;n_step.y=n_y;n_step.currentUsedTime = t_step.currentUsedTime+1;q.push(n_step);}}}} }int MyAdd(int x,int y) {if(x==MAX ||y ==MAX)return MAX;return x+y; } int MyCmp(int x,int y) {return x<y ? x : y; }void main() {while(scanf("%d %d",&n,&m)!=EOF){memset(map,wall,sizeof(map));memset(dY,0,sizeof(dY));memset(dM,0,sizeof(dM));int recordKFC[40000][2];int k=0;for(int i=1;i<=n;i++)for(int j=1;j<=m;j++){cin>>map[i][j];if(map[i][j] == Y){YposX = i;YposY=j;}if(map[i][j] == M){MposX = i;MposY=j;}if(map[i][j] == KFC){dY[i][j] = dM[i][j] = MAX;recordKFC[k][0] = i;recordKFC[k][1] = j;k++;}}BFSSearch(Y);BFSSearch(M);int re = MAX;for(int x=0;x<k;x++)re = MyCmp(re, MyAdd(dY[ recordKFC[x][0] ] [ recordKFC[x][1] ],dM[ recordKFC[x][0] ] [ recordKFC[x][1] ] ));cout<<11*re<<endl;} }?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/kbyd/archive/2013/04/20/3032273.html
總結(jié)
以上是生活随笔為你收集整理的[HDU] 2612 Find a way - 用单源最短论经模拟的简单广搜的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows Socket 编程
- 下一篇: PushYourself