题意:青蛙要从点1出发到点2去,每条边之间距离为权值,中间可能经过很多点,有不同路径,问每条1到2可行路中某一条路径的最大值的最小情况是多少。类似最短路问题,更改一下几个变量定义,用dijkstra,floyed都可以做,也可以等价求最小生成树里最大边的问题。
dijkstra
这里dist[i]定义是,第i个点到起点路径中最大边的边,由于求的是最小的情况,松弛还是用每次确定的最短边进行松弛!
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
double dist[210];
bool visit[210];
const double inf=99999999;
struct Point
{
int x,y;
}point[210];
double Distance(Point a,Point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
int main()
{
int cnt=0;
while(~scanf("%d",&n)&&n)
{
cnt++;
for(int i=1;i<=n;i++)
scanf("%d %d",&point[i].x,&point[i].y);
memset(visit,false,sizeof(visit));
for(int i=1;i<=n;i++)
dist[i]=inf;
dist[1]=0;
for(int i=1;i<=n;i++)
{
int minn=inf,index;
for(int j=1;j<=n;j++)
{
if(!visit[j]&&dist[j]<minn)
{
minn=dist[j];
index=j;
}
}
visit[index]=1;
for(int j=1;j<=n;j++)
{
if(!visit[j]&&dist[j]>max(dist[index],Distance(point[j],point[index])))
dist[j]=max(dist[index],Distance(point[j],point[index]));
}
}
printf("Scenario #%d\n",cnt);
printf("Frog Distance = %.3f\n\n",dist[2]);
}
return 0;
}
floyed
这里M[i][j]定义是i j两点间最大边的松弛后最小值, M[i][j]=min(M[i][j],max(M[i][k],M[k][j]));。时间复杂度n^3,由于这题只有200个数据,可以用!
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
double M[210][210];
const double inf=99999999;
struct Point
{
int x,y;
}point[210];
double Distance(Point a,Point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
void floyd()
{
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
M[i][j]=min(M[i][j],max(M[i][k],M[k][j]));
}
int main()
{
int cnt=0;
while(~scanf("%d",&n)&&n)
{
cnt++;
for(int i=1;i<=n;i++)
scanf("%d %d",&point[i].x,&point[i].y);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
M[i][j]=(double)Distance(point[i],point[j]);
floyd();
printf("Scenario #%d\n",cnt);
printf("Frog Distance = %.3f\n\n",M[1][2]);
}
return 0;
}
最小生成树
构建一个最小生成树,输出最大值!bingo
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m;
double dist[210],ans;
bool visit[210];
const double inf=99999999;
struct Point
{
int x,y;
}point[210];
double Distance(Point a,Point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
void prime()
{
ans=0;
memset(visit,0,sizeof(visit));
for(int i=1;i<=n;i++)
dist[i]=Distance(point[1],point[i]);
visit[1]=1;
for(int i=1;i<=n-1;i++)
{
double minn=99999999.0;int index;
for(int j=1;j<=n;j++)
{
if(!visit[j]&&dist[j]<minn)
{
index=j;
minn=dist[j];
}
}
visit[index]=1;
ans=max(ans,minn);
if(index==2)break;
for(int j=1;j<=n;j++)
{
if(!visit[j]&&dist[j]>Distance(point[index],point[j]))
dist[j]=Distance(point[index],point[j]);
}
}
}
int main()
{
int cnt=0;
while(~scanf("%d",&n)&&n)
{
cnt++;
for(int i=1;i<=n;i++)
scanf("%d %d",&point[i].x,&point[i].y);
prime();
printf("Scenario #%d\n",cnt);
printf("Frog Distance = %.3f\n\n",ans);
}
return 0;
}