题目链接:https://www.luogu.org/problemnew/show/P4568
思路:分层图模板题。分层图讲解,点我。
第一种方法:
#include
#include
#include
#include
#include
#include
#define ll long long
#define inf 0x3f3f3f3f
#define pii pair
const int mod = 1e9+7;
const int maxn = 6e6+7;
using namespace std;
struct node {int to,w,next;} edge[maxn];
int head[maxn], cnt;
int dis[maxn], vis[maxn];
int n, m, s, t, k;
struct Dijkstra
{
void init()
{
memset(head,-1,sizeof(head));
memset(dis,0x3f,sizeof(dis));
memset(vis,0,sizeof(vis));
cnt = 0;
}
void add(int u,int v,int w)
{
edge[cnt].to = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt ++;
}
void dijkstra()
{
priority_queue,greater > q;
dis[s] = 0; q.push({dis[s],s});
while(!q.empty())
{
int now = q.top().second;
q.pop();
if(vis[now]) continue;
vis[now] = 1;
for(int i = head[now]; i != -1; i = edge[i].next)
{
int v = edge[i].to;
if(!vis[v] && dis[v] > dis[now] + edge[i].w)
{
dis[v] = dis[now] + edge[i].w;
q.push({dis[v],v});
}
}
}
}
}dj;
int main()
{
while(~scanf("%d%d%d", &n, &m, &k))
{
dj.init(); scanf("%d%d",&s,&t);
while(m--)
{
int u, v, w;
scanf("%d%d%d",&u, &v, &w);
for(int i = 0; i <= k; i++)
{
dj.add(u + i * n, v + i * n, w);
dj.add(v + i * n, u + i * n, w);
if(i != k)
{
dj.add(u + i * n, v + (i + 1) * n, 0);
dj.add(v + i * n, u + (i + 1) * n, 0);
}
}
}
dj.dijkstra(); int ans = inf;
for(int i = 0; i <= k; i++)
ans = min(ans, dis[t + i * n]);
printf("%d\n",ans);
}
}
第二种方法:
#include
#include
#include
#include
#include
#include
#define ll long long
#define inf 0x3f3f3f3f
#define pii pair
const int mod = 1e9+7;
const int maxn = 1e5+7;
using namespace std;
struct node{int to, w, next, cost; } edge[maxn];
int head[maxn], cnt;
int dis[maxn][15], vis[maxn][15];
int n, m, s, t, k;
struct Dijkstra
{
void init()
{
memset(head,-1,sizeof(head));
memset(dis,127,sizeof(dis));
memset(vis,0,sizeof(vis));
cnt = 0;
}
void add(int u,int v,int w)
{
edge[cnt].to = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt ++;
}
void dijkstra()
{
priority_queue , greater > q;
dis[s][0] = 0;
q.push({0, s});
while(!q.empty())
{
int now = q.top().second; q.pop();
int c = now / n; now %= n;
if(vis[now][c]) continue;
vis[now][c] = 1;
for(int i = head[now]; i != -1; i = edge[i].next)
{
int v = edge[i].to;
if(!vis[v][c] && dis[v][c] > dis[now][c] + edge[i].w)
{
dis[v][c] = dis[now][c] + edge[i].w;
q.push({dis[v][c], v + c * n});
}
}
if(c < k)
{
for(int i = head[now]; i != -1; i = edge[i].next)
{
int v = edge[i].to;
if(!vis[v][c+1] && dis[v][c+1] > dis[now][c])
{
dis[v][c+1] = dis[now][c];
q.push({dis[v][c+1], v + (c + 1) * n});
}
}
}
}
}
}dj;
int main()
{
while(~scanf("%d%d%d", &n, &m, &k))
{
dj.init(); scanf("%d%d",&s,&t);
while(m--)
{
int u, v, w;
scanf("%d%d%d",&u, &v, &w);
dj.add(u, v, w);
dj.add(v, u, w);
}
dj.dijkstra();
int ans = inf;
for(int i = 0; i <= k; i++)
ans = min(ans, dis[t][i]);
printf("%d\n", ans);
}
}
/*
5 6 1
0 4
0 1 5
1 2 5
2 3 5
3 4 5
2 3 3
0 2 100
*/