版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26760433/article/details/84825810
这题也可以用Dijkstra算法做,我用prim做出来的,个人感觉prim更适合这道题。找到最小生成树里的最长边即可。注意并不是所有点都需要建成最小生成树,到达终点就可以终止了。我习惯用邻接表,而且顶点是从0开始的。
贴代码
//Memory 924k Time 32ms
#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
using namespace std;
class road
{
public:
int end;
double weight;
};
class Graph
{
public:
int v; //顶点个数
int mark[210]; //标记是否访问过,访问过为1,否则为0
vector<road> *adj; //邻接表
Graph(int n); //构造函数
~Graph(); //析构函数
void addEdge(int b,int e,double w); //添加边
};
Graph::Graph(int n)
{
v=n;
adj=new vector<road>[n];
}
Graph::~Graph()
{
delete []adj;
}
void Graph::addEdge(int b,int e,double w) //添加边
{
road r1;
r1.end = e;
r1.weight = w;
adj[b].push_back(r1);
}
class Dist
{
public:
int pre;
double length;
int index;
friend bool operator<(const Dist &a,const Dist &b)
{
return a.length>b.length;
}
};
double prim(Graph &g,int s) //s是起始点
{
double max_l=-1<<30;
Dist * D = new Dist[g.v]; //申请空间
for(int i=0;i<g.v;i++) //初始化
{
D[i].index = i;
D[i].length = 1<<30;
D[i].pre = s;
}
priority_queue<Dist> aqueue;
int now_node = s;
for(int i=0;i<g.v-1;i++)
{
vector<road>::iterator ii = g.adj[now_node].begin();
for(;ii!=g.adj[now_node].end();ii++) //刷新与now_node相邻的顶点的值
{
if( g.mark[ii->end]==0 && D[ii->end].length > ii->weight )
{
D[ii->end].length = ii->weight;
D[ii->end].pre = now_node;
aqueue.push(D[ii->end]);
}
}
Dist d;
bool FOUND=false;
while(!aqueue.empty())
{
d = aqueue.top();
aqueue.pop();
if( g.mark[d.index]== 0)
{
break;
}
}
g.mark[now_node]=1;
now_node=d.index;
max_l = max(max_l,d.length);
if(now_node==1) //到达终点
break;
}
return max_l;
}
int main()
{
int n;
int num=1;
int x[210];
int y[210];
double temp;
while(cin>>n)
{
if(n==0)
break;
Graph g(n);
memset(g.mark,0,sizeof(g.mark));
memset(x,0,sizeof(x));
memset(y,0,sizeof(y));
for(int i=0;i<n;i++)
{
cin>>x[i]>>y[i];
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
continue;
temp = sqrt( (double)(x[i]-x[j])*(x[i]-x[j]) +(double)(y[i]-y[j])*(y[i]-y[j]) );
g.addEdge(i,j,temp);
}
}
temp=prim(g,0);
cout<<"Scenario #"<<num<<endl;
printf("Frog Distance = %.3lf\n",temp);;
cout<<endl;
num++;
}
cout<<endl;
return 0;
}