大意题面里很清楚了……
难得没wa就过了的题啊,大哭
建图方式见网络提速
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#define LL long long
#define INF 2147483647
using namespace std;
const int MAXN = 200000 + 50;
int n,m,k,S,T;
int head[MAXN],next[MAXN << 1],dis[MAXN][11],tot;
void init(int n)
{
for(int i = 0;i <= n;i ++)
{
head[i] = -1;
for(int j = 0;j <= k;j ++)
{
dis[i][j] = INF;
}
}
}
struct edge
{
int f,t,v;
bool free;
}l[MAXN << 1];
void build(int f,int t,int v,int free)
{
l[++ tot] = (edge){f,t,v,free};
next[tot] = head[f];
head[f] = tot;
}
int a,b,c;
struct zt
{
int num,dis,cost;
};
bool operator < (zt a,zt b)
{
return a.dis > b.dis;
}
priority_queue <zt> q;
bool used[MAXN][11];
void dij(int x)
{
dis[x][0] = 0;
q.push((zt){x,0,0});
while(!q.empty())
{
zt u = q.top();
q.pop();
used[u.num][u.cost] = true;
if(u.num == T && u.cost == k)return;
for(int i = head[u.num];i != -1;i = next[i])
{
int t = l[i].t;
if(dis[t][u.cost + l[i].free] > dis[u.num][u.cost] + l[i].v && u.cost + l[i].free <= k)
{
dis[t][u.cost + l[i].free] = dis[u.num][u.cost] + l[i].v;
q.push((zt){t,dis[t][u.cost + l[i].free],u.cost + l[i].free});
}
}
}
}
int main()
{
scanf("%d%d%d%d%d",&n,&m,&k,&S,&T);
init(n);
for(int i = 1;i <= m;i ++)
{
scanf("%d%d%d",&a,&b,&c);
build(a,b,c,0);
build(b,a,c,0);
build(a,b,0,1);
build(b,a,0,1);
}
dij(S);
printf("%d",dis[T][k]);
return 0;
}
这里贴一份wyh大佬的代码,建图有点微妙的不同:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int MAXN = 100000 + 5;
const int INF = 2147483645;
struct edge
{
int f,t,v;
}l[MAXN << 1];
bool used[MAXN][15];
int n,m,s,e,k,f,t,v;
int dis[MAXN][15],first[MAXN],next[MAXN],tot;
void init()
{
tot = 0;
memset(first,-1,sizeof(first));
scanf("%d%d%d%d%d",&n,&m,&k,&s,&e);
for(int i = 0;i <= n;i ++)
for(int j = 0; j <= k;j ++)
dis[i][j] = INF;
}
void build(int f,int t,int v)
{
l[++ tot] = (edge){f,t,v};
next[tot] = first[f];
first[f] = tot;
}
queue <int> q,p;
void spfa(int s)
{
dis[s][0] = 0;
used[s][0] = 1;
q.push(s);p.push(0);
while(!q.empty())
{
int x = q.front();
int cnt = p.front();
q.pop();p.pop();
used[x][cnt] = 0;
for(int i = first[x]; i != -1; i = next[i])
{
int u = l[i].t;
if(dis[u][cnt] > dis[x][cnt] + l[i].v)
{
dis[u][cnt] = dis[x][cnt] + l[i].v;
if(!used[u][cnt])
{
q.push(u);
p.push(cnt);
used[u][cnt] = 1;
}
}
if(cnt < k)
{
if(dis[u][cnt + 1] > dis[x][cnt])
{
dis[u][cnt + 1] = dis[x][cnt];
if(!used[u][cnt + 1])
{
q.push(u);
p.push(cnt + 1);
used[u][cnt + 1] = 1;
}
}
}
}
}
return;
}
int main()
{
init();
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d",&f,&t,&v);
build(f,t,v);
build(t,f,v);
}
spfa(s);
printf("%d\n",dis[e][k]);
return 0;
}