题目链接:点击查看
题意:n的点,前k个点组成一个完全图,距离为x,然后给出m条边,求s到所有点的最短路
题解:当遇到一个小于等于k的点时,枚举1-k的点更新一下,后面再遇到1-k的点时就不会更新了,所以更新过一次后标记一下即可
另一种思路就是在设一个点,1-k的点到他就是0,他到1-k就是x,这样也是只更新一遍
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
struct node{
int to,nex;
int d;
}e[N * 2];
ll dis[N];
int vis[N];
int n,k,x,m,s;
int head[N],len;
void init()
{
len=0;
for(int i=0;i<=n;i++)
{
vis[i]=0;
dis[i]=1e18;
head[i]=-1;
}
}
void add(int x,int y,int z)
{
e[len].to=y;
e[len].d=z;
e[len].nex=head[x];
head[x]=len++;
}
struct node1{
int to;
ll d;
node1(){
}
node1(int to_,ll d_)
{
to=to_;
d=d_;
}
bool operator <(const node1 &xx)const
{
return d>xx.d;
}
};
void DIJ()
{
priority_queue<node1> q;
node1 now;
q.push(node1(s,0));
dis[s]=0;
int flag=0;
while(!q.empty())
{
now=q.top();q.pop();
if(vis[now.to]) continue;
vis[now.to]=1;
for(int i=head[now.to];i!=-1;i=e[i].nex)
{
int to=e[i].to;
if(!vis[to] && dis[to]>dis[now.to] + e[i].d)
{
dis[to]=dis[now.to]+e[i].d;
q.push(node1(to,dis[to]));
}
}
if(now.to<=k && flag==0)
{
flag=1;
for(int i=1;i<=k;i++)
{
if(i==now.to) continue;
int to=i;
if(!vis[to] && dis[to]>dis[now.to] + x)
{
dis[to]=dis[now.to]+x;
q.push(node1(to,dis[to]));
}
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d%d%d",&n,&k,&x,&m,&s);
init();
int x,y,z;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
add(y,x,z);
}
DIJ();
for(int i=1;i<=n;i++)
printf("%lld%c",dis[i]," \n"[i==n]);
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
struct node{
int to,nex;
int d;
}e[N * 4];
ll dis[N];
int vis[N];
int n,k,x,m,s;
int head[N],len;
void init()
{
len=0;
for(int i=0;i<=n;i++)
{
vis[i]=0;
dis[i]=1e18;
head[i]=-1;
}
}
void add(int x,int y,int z)
{
e[len].to=y;
e[len].d=z;
e[len].nex=head[x];
head[x]=len++;
}
struct node1{
int to;
ll d;
node1(){
}
node1(int to_,ll d_)
{
to=to_;
d=d_;
}
bool operator <(const node1 &xx)const
{
return d>xx.d;
}
};
void DIJ()
{
priority_queue<node1> q;
node1 now;
q.push(node1(s,0));
dis[s]=0;
while(!q.empty())
{
now=q.top();q.pop();
if(vis[now.to]) continue;
vis[now.to]=1;
for(int i=head[now.to];i!=-1;i=e[i].nex)
{
int to=e[i].to;
if(!vis[to] && dis[to]>dis[now.to] + e[i].d)
{
dis[to]=dis[now.to]+e[i].d;
q.push(node1(to,dis[to]));
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d%d%d",&n,&k,&x,&m,&s);
init();
for(int i=1;i<=k;i++)
{
add(0,i,x);
add(i,0,0);
}
for(int i=1;i<=m;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
add(y,x,z);
}
DIJ();
for(int i=1;i<=n;i++)
printf("%lld%c",dis[i]," \n"[i==n]);
}
return 0;
}