https://nanti.jisuanke.com/t/31001
There are NN cities in the country, and MM directional roads from uu to v(1\le u, v\le n)v(1≤u,v≤n). Every road has a distance c_ici. Haze is a Magical Girl that lives in City 11, she can choose no more than KK roads and make their distances become 00. Now she wants to go to City NN, please help her calculate the minimum distance.
Input
The first line has one integer T(1 \le T\le 5)T(1≤T≤5), then following TT cases.
For each test case, the first line has three integers N, MN,M and KK.
Then the following MM lines each line has three integers, describe a road, U_i, V_i, C_iUi,Vi,Ci. There might be multiple edges between uu and vv.
It is guaranteed that N \le 100000, M \le 200000, K \le 10N≤100000,M≤200000,K≤10,
0 \le C_i \le 1e90≤Ci≤1e9. There is at least one path between City 11 and City NN.
Output
For each test case, print the minimum distance.
样例输入复制
1 5 6 1 1 2 2 1 3 4 2 4 3 3 4 1 3 5 6 4 5 2
样例输出复制
3
题目来源
题意:
求从1到n的路径中,更新至多k条路长度变为0,求从1到n的最短路径
分析:
套用Dijkstra模板
dis[i][j]代表到第i点更新j条边的最短路径
状态转移方程
dis[v[i].to][j]=min(dis[v[i].to][j],dis[i][j]+v[i].distance);
dis[v[i].to][j+1]=min(dis[v[i].to][j+1],dis[i][j]);
代码:
#include<bits/stdc++.h>
#define maxn 200005
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
int n, m, k,head[200005],cnt;
struct node
{
int to ,too;
ll distance;
}v[200005];
void add(int uu,int vv,ll val)
{
v[cnt].to=vv;
v[cnt].too=head[uu];
v[cnt].distance=val;
head[uu]=cnt;
cnt++;
}
bool book[100045][15];
ll dis[100405][15];
struct NNode
{
int id,to,diss;
bool operator<(const NNode &aa)const
{
return diss>aa.diss;
}
};
void myinit()
{
cnt=0;
memset(head,-1,sizeof(head));
memset(book, 0, sizeof(book));
for(int i=0;i<=n;i++)
for(int j=0;j<=k;j++)
dis[i][j]=10000000000000000;
}
void SPFA(int s)
{
priority_queue<NNode> q;
NNode now,next;
for(int i=0;i<=k;i++){
now.to=s;
now.id=i;
now.diss=0;
q.push(now);
dis[s][i]=0;
}
int pos;
while(!q.empty())
{
int point;
now= q.top();
q.pop();
pos=now.id;
point=now.to;
if(book[point][now.id])
continue;
book[point][now.id]=1;
for(int i = head[point]; i !=-1; i=v[i].too)
{
if(pos<k&&dis[point][pos] < dis[v[i].to][pos+1])
{
dis[v[i].to][pos+1] = dis[point][pos];
if(!book[v[i].to][pos+1])
{
next.id=pos+1;
next.to=v[i].to;
next.diss=dis[v[i].to][pos+1];
q.push(next);
}
}
if(pos<=k&&v[i].distance + dis[point][pos] < dis[v[i].to][pos])
{
dis[v[i].to][pos] = dis[point][pos] + v[i].distance;
if(!book[v[i].to][pos])
{
next.id=pos;
next.to=v[i].to;
next.diss=dis[v[i].to][pos];
q.push(next);
}
}
}
}
}
int x[maxn],y[maxn];
ll d[maxn];
int main()
{
int i, j;
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d",&n,&m,&k);
myinit();
for(i = 0; i < m; i++)
{
scanf("%d%d%lld", &x[i], &y[i], &d[i]);
if(x[i]!=y[i])
add(x[i],y[i],d[i]);
}
dis[1][0] = 0;
SPFA(1);
ll ans;
ans=dis[n][0];
for( i=0; i<=k; i++)
{
ans=min(ans,dis[n][i]);
}
printf("%lld\n",ans);
}
return 0;
}