对于30%的数据,2<=n<=50,1<=m<=300,k=0;
对于50%的数据,2<=n<=600,1<=m<=6000,0<=k<=1;
对于100%的数据,2<=n<=10000,1<=m<=50000,0<=k<=10.
我们用dis[i][j]表示走到i节点时免费j次取到的最小花费,之后加上堆优化,要不然T到死去活来~
CODE
# include
# include
# include
# include
using namespace std;
const int MAXM(50050);
const int MAXN(10010);
const int MAXK(20);
inline int Max(int a,int b) {
return a > b ? a : b;
}
inline int Min(int a,int b) {
return a < b ? a : b;
}
int n,m,k,tot,st,en,ans = 0x7fffffff;
int h[MAXN];
int dis[MAXN][MAXK];
bool vis[MAXN][MAXK];
struct Edge {
int v,w,next,u;
} e[MAXM << 1];
struct flight {
int ver,step,dis;
bool friend operator < (flight a,flight b) {
return a.dis > b.dis;
}
};
void add(int u,int v,int w) {
e[++tot].u = u;
e[tot].v = v;
e[tot].w = w;
e[tot].next = h[u];
h[u] = tot;
}
void work1() {
int diss[MAXN];
memset(diss,0x3f,sizeof(diss));
bool viss[MAXN] = {0};
queue q;
q.push(st);
diss[st] = 0;
viss[st] = 1;
while(!q.empty()) {
int u = q.front();
q.pop();
viss[u] = 0;
for(int i = h[u]; i; i = e[i].next) {
int v = e[i].v;
if(diss[v] > diss[u] + e[i].w) {
diss[v] = diss[u] + e[i].w;
if(!viss[v]) {
viss[v] = 1;
q.push(v);
}
}
}
}
printf("%d",diss[en]);
}
void work2() {
memset(dis,0x3f,sizeof(dis));
priority_queue q;
flight last,now;
last.ver = st;
last.step = 0;
last.dis = 0;
dis[last.ver][last.step] = 0;
q.push(last);
vis[last.ver][last.step] = 1;
while(!q.empty()) {
now = q.top();
q.pop();
vis[now.ver][now.step] = 0;
for(int i = h[now.ver];i;i = e[i].next) {
int v = e[i].v;
if(now.step + 1 <= k) {
if(dis[v][now.step + 1] > dis[now.ver][now.step]) {
dis[v][now.step + 1] = dis[now.ver][now.step];
if(!vis[v][now.step + 1]) {
vis[v][now.step + 1] = 1;
q.push((flight){v,now.step + 1,dis[v][now.step + 1]});
}
}
}
if(dis[v][now.step] > dis[now.ver][now.step] + e[i].w) {
dis[v][now.step] = dis[now.ver][now.step] + e[i].w;
if(!vis[v][now.step]) {
vis[v][now.step] = 1;
q.push((flight){v,now.step,dis[v][now.step]});
}
}
}
}
for(int i = 0; i <= k; ++i) ans = Min(dis[en][i],ans);
printf("%d",ans);
}
void init() {
int i,u,v,w;
scanf("%d%d%d%d%d",&n,&m,&k,&st,&en);
st++;
en++;
for(i = 1; i <= m; ++i) {
scanf("%d%d%d",&u,&v,&w);
u++;
v++;
add(u,v,w);
add(v,u,w);
}
if(k == 0) work1();
else work2();
}
int main() {
init();
}