RQNOJ 86 智捅马蜂窝【解题报告】SPFA做法

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn = 105;
struct edge{int y;double t;int next;}e[100000];
int n,k=1;
int v;
int head[maxn],x[maxn],y[maxn],vis[maxn];
double dis[maxn];
queue<int> q;
void adde(int x,int y,double z)
{
	e[k].y=y;
	e[k].t=z;
	e[k].next=head[x];
	head[x]=k++;
}
double dist(int i,int j){
	int dx = x[i]-x[j],dy = y[i] - y[j];
	return sqrt(dx * dx + dy * dy);
}
int main()
{
	scanf("%d %d",&n,&v);
	int z;
	memset(head,-1,sizeof(head));
	for(int i=1;i<=n;i++)dis[i]=1e9;
	for(int i=1;i<=n;i++)
	{
		scanf("%d%d%d",&x[i],&y[i],&z);
		if(z)
		{
			adde(z,i,dist(i,z)*1.0/v);
			adde(i,z,dist(i,z)*1.0/v);
		}
		else
		adde(0,1,0);
	}
	for(int i = 1;i <= n;i++)
	 for(int j = 1;j <= n;j++)
		if(x[i]==x[j] && y[i] < y[j])
		adde(j,i,sqrt((y[j]-y[i])*2/10.0));	
	dis[1]=0;
	vis[1]=1;
	q.push(1);
	int p = 0;
	while(!q.empty())
	{
		int u = q.front();q.pop();
		vis[u] = 0;
		for(int cnt = head[u];cnt!=-1;cnt=e[cnt].next)
		{
			p = e[cnt].y;
			if(dis[p]>dis[u]+e[cnt].t)
			{
				dis[p] = dis[u]+e[cnt].t;
				if(!vis[p])
				{
					q.push(p);
					vis[p]=1;
				}
			}
		}
	}
	printf("%.2lf",dis[n]);
	return 0;
}

你可能感兴趣的:(算法,图论,SPFA,单源最短路)