Description
n个点,m条双向边,有k次免费的机会,问最短路。
Sample Input
5 6 1
0 4
0 1 5
1 2 5
2 3 5
3 4 5
2 3 3
0 2 100
Sample Output
8
这道题基本算法是spfa,但需要定一个f的二维数组,f[i][j] 表示到编号为i的点用j次免费的机会的最小值。在spfa中要分两种情况(免费和不免费)。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
int x,y,c,next;
}a[210000];int len,last[110000];
void ins(int x,int y,int c)
{
len++;
a[len].x=x;a[len].y=y;a[len].c=c;
a[len].next=last[x];last[x]=len;
}
int f[110000][11];
bool v[110000][11];
int list[110000][11],st,ed;
int main()
{
int n,m,kk;
scanf("%d%d%d",&n,&m,&kk);
scanf("%d%d",&st,&ed);
for(int i=1;i<=m;i++)
{
int x,y,c;
scanf("%d%d%d",&x,&y,&c);
ins(x,y,c);ins(y,x,c);
}
memset(f,9999999,sizeof(f));
memset(v,true,sizeof(v));
memset(list,0,sizeof(list));
int head,tail;
list[1][0]=st;list[1][1]=0;v[st][0]=false;
head=1,tail=2;f[st][0]=0;
while(head!=tail)
{
int x=list[head][0],c=list[head][1];
for(int k=last[x];k;k=a[k].next)
{
int y=a[k].y;
if(f[x][c]+a[k].c<f[y][c])//不用免费机会
{
f[y][c]=f[x][c]+a[k].c;
if(v[y][c]!=false)
{
v[y][c]=false;
list[tail][0]=y;list[tail][1]=c;
tail++;
if(tail==100000+1)tail=1;
}
}
if(f[x][c]<f[y][c+1] && c<kk)//要免费机会
{
f[y][c+1]=f[x][c];
if(v[y][c+1]!=false)
{
v[y][c+1]=false;
list[tail][0]=y;list[tail][1]=c+1;
tail++;
if(tail==100000+1)tail=1;
}
}
}
v[x][c]=true;
head++;if(head==100000+1)head=1;
}
int s=9999999;
for(int i=0;i<=kk;i++)
{
s=min(s,f[ed][i]);
}
printf("%d\n",s);
return 0;
}