Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10852 | Accepted: 3583 |
Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11 首先要注意的一点是n m后面可能跟了空格,然后行数和列数超过50, 这题就是先bfs找出任意两个A和A,或者A和S之间的最短路程,然后利用最小生成树进行求解#include <map> #include <set> #include <stack> #include <queue> #include <cmath> #include <ctime> #include <vector> #include <cstdio> #include <cctype> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; #define INF 0x3f3f3f3f #define inf -0x3f3f3f3f #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define mem0(a) memset(a,0,sizeof(a)) #define mem1(a) memset(a,-1,sizeof(a)) #define mem(a, b) memset(a, b, sizeof(a)) #define Hash(a,b) (a-1)*m+b typedef long long ll; const int maxn=150; int f[12510]; char mp[151][151]; int vis[101][101]; int n,m; int dir[4][2]={-1,0,1,0,0,1,0,-1}; struct Edge{ int from,to,dis; }e[250*250]; bool cmp(Edge a,Edge b){ return a.dis<b.dis; } struct node{ int x,y,count1; }ans[maxn]; bool over(int x,int y){ if(x<=0||y<=0||x>n|y>m) return true; return false; } int find(int x){ int k, j, r; r = x; while(r!=f[r]) //查找跟节点 r = f[r]; //找到跟节点,用r记录下 k = x; while(k != r){ //非递归路径压缩操作 j = f[k]; //用j暂存parent[k]的父节点 f[k] = r; //f[x]指向跟节点 k = j; //k移到父节点 } return r; //返回根节点的值 } int main(){ int t; scanf("%d",&t); while(t--){ scanf("%d%d",&m,&n); int cnt=0; char c=getchar(); while(c==' '){ c=getchar(); } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ mp[i][j]=getchar(); if(mp[i][j]=='A'||mp[i][j]=='S'){ ans[cnt].x=i; ans[cnt++].y=j; } } getchar(); } int cnt1=0; for(int i=0;i<cnt;i++){ mem0(vis); queue<node>Q; while(!Q.empty()){ Q.pop(); } vis[ans[i].x][ans[i].y]=1; Q.push((node){ans[i].x,ans[i].y,0}); while(!Q.empty()){ node a=Q.front(); Q.pop(); for(int j=0;j<4;j++){ int x=a.x+dir[j][0]; int y=a.y+dir[j][1]; if(over(x,y)||mp[x][y]=='#'||vis[x][y]==1) continue; if(mp[x][y]=='A'||mp[x][y]=='S'){ e[cnt1].from=Hash(ans[i].x,ans[i].y); e[cnt1].to=Hash(x,y); e[cnt1++].dis=a.count1+1; } vis[x][y]=1; Q.push((node){x,y,a.count1+1}); } } } for(int i=1;i<=n*n;i++) f[i]=i; sort(e,e+cnt1,cmp); int ans=0; for(int i=0;i<cnt1;i++){ int u=e[i].from,v=e[i].to,w=e[i].dis; int t1=find(u); int t2=find(v); if(t1!=t2){ ans+=w; f[t1]=t2; } } printf("%d\n",ans); } return 0; }