J - Borg Maze

思路:bfs+最小生成树。
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAXN 110
using namespace std;
int fa[MAXN];
struct nond{
    int x,y,z;
}v[MAXN*MAXN];
struct none{
    int x,y,z;
};
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int t,n,m,tot,sum,ans,point;
int map[MAXN][MAXN],vis[MAXN][MAXN];
void bfs(int x,int y){
    queue<none>que;none s;s.x=x;s.y=y;s.z=0;
    memset(vis,0,sizeof(vis));vis[x][y]=1;
    que.push(s);int k=1;
    while(!que.empty()){
        none now=que.front();
        que.pop();
        for(int i=0;i<4;i++){
            int cx=now.x+dx[i];
            int cy=now.y+dy[i];
            int cz=now.z+1;
            if(cx>=1&&cx<=n&&cy>=1&&cy<=m&&map[cx][cy]>=0&&!vis[cx][cy]){
                if(map[cx][cy]>0){ v[++tot].x=map[x][y];v[tot].y=map[cx][cy];v[tot].z=cz;k++; }
                if(k==point)    return ;
                none tmm;tmm.x=cx;tmm.y=cy;tmm.z=cz;
                vis[cx][cy]=1;que.push(tmm);
            }
        }
    }
}
int cmp(nond a,nond b){
    return a.z<b.z;
}
int find(int x){
    if(fa[x]==x)    return x;
    else return fa[x]=find(fa[x]);
}
int main(){
    scanf("%d",&t);
    char tmp[MAXN];
    while(t--){
        scanf("%d%d",&m,&n);
        gets(tmp);
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                char x;scanf("%c",&x);
                if(x=='#') map[i][j]=-1;
                else if(x==' ')    map[i][j]=0;
                else map[i][j]=++point;
            }
            char c;scanf("%c",&c);
        }
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                if(map[i][j]>0)    bfs(i,j);
        sort(v+1,v+1+tot,cmp);
        for(int i=1;i<=point;i++)    fa[i]=i;
        for(int i=1;i<=tot;i++){
            int dx=find(v[i].x);
            int dy=find(v[i].y);
            if(dx==dy)    continue;
            fa[dy]=dx;sum++;
            ans+=v[i].z;
            if(sum==point-1)    break;
        }
        cout<<ans<<endl;
        ans=0;tot=0;sum=0;point=0;
    }
}

 

posted @ 2018-02-23 19:15  一蓑烟雨任生平  阅读(134)  评论(0编辑  收藏  举报