POJ-3026
题意:给一个n*m的地图,里面有一个S和若干个A,问从S到所有的A的距离之和最短(S可以无限在任意时刻分身,但是每秒只能移动一个分身)
思路:由于S可以随时随地分身,那么其实就是求令所有的A和S连通的最小路径和;所以我们先用BFS求每个A或S到其他所有A或S的最短距离,然后求一个最小生成树即可
#include<iostream>
#include<cstdlib>
#include<sstream>
#include<cstdio>
#include<stack>
#include<cstdio>
#include<map>
#include<set>
#include<queue>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long LL;
#define me(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
const int N=2111122;
const int M=20005;
const int H = 750;
int p[M],v[H][H],stemp[H][H],v_1[H][H];
int f1[4] = {0,0,1,-1};
int f2[4] = {1,-1,0,0};
char s[H][H];
int sum,o,n,m,cond;
struct node {
int x,y;
};
struct node_1 {
int l,r,ans;
}a[M];
bool cmp(node_1 a,node_1 b) {
return a.ans < b.ans;
}
int find(int root) {
return root == p[root]?root:p[root] = find(p[root]);
}
void kruskal() {
int i,ct=0;
for(i = 1 ; i <= cond ; i++)p[i] = i;
sort(a+1,a+1+o,cmp);
for(i = 1 ; i <= o ; i++) {
int x = find(a[i].l);
int y = find(a[i].r);
if(x != y) {
p[x] = y;
ct ++;
sum += a[i].ans;
if(ct == cond-1)break;
}
}
}
queue<node> q;
void bfs(int l,int r) {
memset(v_1,0,sizeof(v_1));
v_1[l][r] = 1;
int fx = l;
int fy = r;
int i;
stemp[l][r] = 0;
while(!q.empty())
q.pop();
node t;
t.x = l;
t.y = r;
q.push(t);
while(!q.empty()) {
node g = q.front();
q.pop();
for(i = 0 ; i < 4 ; i ++) {
int dx = g.x + f1[i];
int dy = g.y + f2[i];
if(dx>=0&&dx<m&&dy>=0&&dy<n) {
if(s[dx][dy] != '#'&&v_1[dx][dy]==0) {
v_1[dx][dy] = 1;
t.x = dx;
t.y = dy;
stemp[dx][dy] = stemp[g.x][g.y]+1;
q.push(t);
if(s[dx][dy]!=' ') {
a[++o].l = vis[dx][dy];
a[o].r = vis[fx][fy];
a[o].ans = stemp[dx][dy];
}
}
}
}
}
}
int main() {
int tt,i,j;
char ch[13];
scanf("%d",&tt);
while(tt--) {
scanf("%d%d",&n,&m);
gets(ch);
cond = 0;
sum=0;
o=0;
for(i = 0 ; i < m ; i++) gets(s[i]);
for(i = 0 ; i < m ; i++) {
for( j = 0 ; j < n; j++) {
if(s[i][j] == 'S'||s[i][j] == 'A') {
vis[i][j] = ++cond;//给每个A或S一个编号,后面求最小生成树用
}
}
}
if(cond <= 1) {
cout << 0 << endl;
return 0;
}
for(i = 0 ; i < m ; i++) {
for( j = 0 ; j < n; j++) {
if(s[i][j] == 'S'||s[i][j] == 'A') {
bfs(i,j);
}
}
}
kruskal();
printf("%d\n",sum);
}
return 0;
}