标签:ring node lan eal collect int cos 最小生成树 space
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 16625 | Accepted: 5383 |
Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
Source
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <map> using namespace std; const int INF=0x3f3f3f3f; char mapp[155][155]; int a[155][155]; int n,m; int dx[4]={1,-1,0,0}; int dy[4]={0,0,1,-1}; struct node{ int x,y; }; int flag[155][155]; bool vis[155]; int minn[155]; int cost[155][155];///记录总的各点到各点的距离 int cnt[155][155];///记录当前点到bfs到其他各点的距离 void bfs(int sx,int sy){ queue<node>q; while(!q.empty())q.pop(); memset(cnt,-1,sizeof(cnt)); cnt[sx][sy]=0; node first; first.x=sx,first.y=sy; q.push(first); while(!q.empty()){ node now=q.front(); q.pop(); if(a[now.x][now.y]!=-1)///记录到全局为生成树做准备 cost[a[sx][sy]][a[now.x][now.y]]=cnt[now.x][now.y]; for(int i=0;i<4;i++){ node next; next.x=now.x+dx[i]; next.y=now.y+dy[i]; if(mapp[next.x][next.y]==‘#‘||cnt[next.x][next.y]!=-1||next.x<0||next.y<0||next.x>=n||next.y>=m)continue; cnt[next.x][next.y]=cnt[now.x][now.y]+1; q.push(next); } } } int prim(int n){ int ans=0; memset(vis,false,sizeof(vis)); vis[0]=true; for(int i=1;i<n;i++)minn[i]=cost[0][i]; for(int i=1;i<n;i++){ int minc=INF; int p=-1; for(int j=0;j<n;j++){ if(!vis[j]&&minc>minn[j]){ minc=minn[j]; p=j; } } ans+=minc; vis[p]=true; for(int j=0;j<n;j++) if(!vis[j]&&minn[j]>cost[p][j]){ minn[j]=cost[p][j]; } }return ans; } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int t; cin>>t; while(t--){ cin>>m>>n; gets(mapp[0]); memset(a,-1,sizeof(a)); int num=0; for(int i=0;i<n;i++){ gets(mapp[i]); for(int j=0;j<m;j++){ if(mapp[i][j]==‘A‘||mapp[i][j]==‘S‘) a[i][j]=num++; } } /* for(int i=0;i<n;i++){ cout<<mapp[i]<<endl; }*/ for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(a[i][j]!=-1){ bfs(i,j); } } } /* for(int i=0;i<num;i++){ for(int j=0;j<num;j++){ cout<<cost[i][j]<<" "; } cout<<endl; }*/ cout<<prim(num)<<endl; } return 0; }
POJ 3026 --Borg Maze(bfs,最小生成树,英语题意题,卡格式)
标签:ring node lan eal collect int cos 最小生成树 space
原文地址:https://www.cnblogs.com/luowentao/p/8973999.html