这题就是k短路的一个模板题,恶心的是题面没说每条路径不能有重复点
题面链接
代码
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<bitset>
#include<bits/stdc++.h>
using namespace std;
#include<queue>
const int inf=1e9;
#define ll long long
#define maxn 505
int n,m;
struct node
{
int to; double w;
friend bool operator<(node a,node b)
{
return a.w>b.w;
}
};
struct nd
{
int x,y;
}a[maxn];
struct nd1
{
int x;double y;
};
double h[maxn];
vector<nd1>e[maxn];
double js(int i,int j)
{
int x=(a[i].x-a[j].x)*(a[i].x-a[j].x)+(a[i].y-a[j].y)*(a[i].y-a[j].y);
return sqrt(x);
}
priority_queue<node>q;int vis[maxn];
void dijk1()
{
for(int i=1;i<=n;i++) h[i]=inf;
q.push({n,0});h[n]=0;
while(!q.empty())
{
int u=q.top().to;q.pop();
if(vis[u]==1) continue;
vis[u]=1;
//printf("h[%d]=%.4f\n",u,h[u]);
for(nd1 i:e[u])
{
int v=i.x;double w=i.y;
if(h[v]>h[u]+w)
{
h[v]=h[u]+w;
//printf(" w=%.4f h[%d]=%.4f\n",w,v,h[v]);
if(vis[v]==0)
{
q.push({v,h[v]});
}
}
}
}
}
struct node1
{
int to;double w;
bitset<maxn>vis;
friend bool operator<(node1 a,node1 b)
{
return a.w+(h[a.to])>b.w+(h[b.to]);
}
};
priority_queue<node1>q1;
void astar()
{
if(h[n]==inf)
{
printf("-1\n");
return ;
}
bitset<maxn>vis0;
vis0[1]=1;
q1.push({1,0.0,vis0});
int f=0;double ans=0.0;
while(!q1.empty())
{
int u=q1.top().to;double s=q1.top().w;
bitset<maxn>vis1(q1.top().vis);
q1.pop();
//printf("u=%d s=%.4f\n",u,s);
//for(int i=1;i<=n;i++) printf("vis1[%d]=%d\n",i,(int)vis1[i]);
if(u==n)
{
f++;
if(f==2)
{
ans=s;
break;
}
}
for(nd1 i:e[u])
{
int v=i.x;double w=(i.y);
if(vis1[v]==1) continue;
bitset<maxn>vis2(vis1);
vis2[v]=1;
//printf(" v=%d w=%.4f\n",v,w);
q1.push({v,s+w,vis2});
}
}
if(f!=2) printf("-1\n");
else printf("%.2f\n",ans);
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d %d",&a[i].x,&a[i].y);
}
for(int i=1;i<=m;i++)
{
int u,v;
scanf("%d %d",&u,&v);
e[u].push_back({v,js(u,v)});
e[v].push_back({u,js(u,v)});
}
dijk1();
astar();
}