题目地址
AC代码
#include <iostream>
#include <algorithm>
#include <utility>
#include <cstring>
#include <queue>
using namespace std;
int main() {
ios::sync_with_stdio(false);
int n;
cin>>n;
for (int i = 0; i < n; ++i) {
int x,y;
cin>>x>>y;
string laji;
getline(cin,laji);
int graph[y][x];
int counter = 0;
for (int j = 0; j < y; ++j) {
string temp;
getline(cin,temp);
for (int k = 0; k < x; ++k) {
if(temp[k]=='#')graph[j][k]=0;
else if(temp[k]==' ')graph[j][k]=-1;
else{
counter++;
graph[j][k]=counter;
}
}
}
int list[counter+1][counter+1],markVertex[counter+1],dist[counter+1];
memset(markVertex,0, sizeof(markVertex));
for (int l = 0; l < y; ++l) {
for (int j = 0; j < x; ++j) {
if(graph[l][j]!=0&&graph[l][j]!=-1){
queue<pair<pair<int,int>,int> >temp;
temp.push(make_pair(make_pair(l,j),0));
int mark[y][x];
memset(mark,0, sizeof(mark));
while(!temp.empty()){
int tx=temp.front().first.second,ty=temp.front().first.first,dis = temp.front().second;
temp.pop();
if(!mark[ty][tx]) {
if (graph[ty][tx] != 0&&ty>=0&&ty<y&&tx>=0&&tx<x) {
if (graph[ty][tx] != -1) {
list[graph[ty][tx]][graph[l][j]] = list[graph[l][j]][graph[ty][tx]] = dis;
}
temp.push(make_pair(make_pair(ty + 1, tx), dis + 1));
temp.push(make_pair(make_pair(ty - 1, tx), dis + 1));
temp.push(make_pair(make_pair(ty, tx + 1), dis + 1));
temp.push(make_pair(make_pair(ty, tx - 1), dis + 1));
}
mark[ty][tx] = 1;
}
}
}
}
}
markVertex[1]=1;
for (int m = 1; m <= counter; ++m) {
dist[m] = list[1][m];
}
int boo = 0,sum=0;
while(1){
if(boo==counter-1)break;
boo++;
int mini = 65333,pos;
for (int j = 1; j <= counter; ++j) {
if(markVertex[j])continue;
if(dist[j]<mini){
mini = dist[j];
pos = j;
}
}
sum +=mini;
markVertex[pos]=1;
for (int k = 1; k <= counter; ++k) {
if(markVertex[k])continue;
if(list[pos][k]<dist[k])dist[k]=list[pos][k];
}
}
cout<<sum<<endl;
}
return 0;
}
吐槽
讲真,我是真的没想明白这个数据是怎么给的,要不是看discuss知道了x和y后面有一大串空格,我还得在OJ上RE半天,槽点满满
我是自己想不出来为什么最小生成树算法就能够满足题意就是了//菜还是你菜。大半夜了神志不清犯了很多小错误,万幸的是在交之前就给找出来了,整个BFS+Prim的算法思路倒是很清晰,就是写起来麻烦,下次直接复制模板(滑稽)