There are NN cities in the country, and MMdirectional 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 become00. 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
就模板题。。。不够好象据说卡了spfa和pair时间,真不巧我全用了。。。t了一次后我就加了优先队列优化过了。
#include<cstdio>
#include<iostream>
#include<queue>
#include<utility>
#include<cstring>
using namespace std;
const long long int inf = 0x3f3f3f3f3f3f3f3f;
struct fuck
{
int to, ne;
long long int len;
}ed[200005];
int vis[100005][12];
long long int d[100005][12];
int head[100005];
int cnt, n, m, k, st, en;
struct cmp {
bool operator()(pair<int, int>a, pair<int, int>b) {
return d[a.first][a.second] > d[b.first][b.second];
}
};
void init(){
memset(vis, 0, sizeof(vis));
for (int s = 0; s <= n; s++){
for (int w = 0; w <= k; w++){
d[s][w] = inf;
}
head[s] = -1;
}
cnt = 0;
}
void add(int from, int to, long long int len)
{
ed[cnt].to = to;
ed[cnt].len = len;
ed[cnt].ne = head[from];
head[from] = cnt++;
}
void spfa()
{
d[st][0] = 0;
vis[st][0] = 1;
priority_queue< pair<int, int>, vector< pair<int, int> >, cmp >q;
q.push(make_pair(st, 0));
while (!q.empty())
{
pair<int, int>t = q.top();
q.pop();
vis[t.first][t.second] = 0;
for (int s = head[t.first]; ~s; s = ed[s].ne)
{
if (d[t.first][t.second] + ed[s].len < d[ed[s].to][t.second])
{
d[ed[s].to][t.second] = d[t.first][t.second] + ed[s].len;
if (!vis[ed[s].to][t.second])
{
vis[ed[s].to][t.second] = 1;
q.push(make_pair(ed[s].to, t.second));
}
}
if (d[t.first][t.second] < d[ed[s].to][t.second + 1] && t.second<k)
{
d[ed[s].to][t.second + 1] = d[t.first][t.second];
if (!vis[ed[s].to][t.second + 1])
{
vis[ed[s].to][t.second + 1] = 1;
q.push(make_pair(ed[s].to, t.second + 1));
}
}
}
}
}
int main()
{
int te;
scanf("%d", &te);
while (te--)
{
scanf("%d%d%d", &n, &m, &k);
init();
st = 1; en = n;
while (m--){
int a, b; long long int c;
scanf("%d%d%lld", &a, &b, &c);
add(a, b, c);
}
spfa();
printf("%lld\n", d[en][k]);
}
return 0;
}
本文介绍了一个经典的最短路径问题,通过使用SPFA算法并结合优先队列进行优化来解决。问题背景为一名住在城市1的魔法少女需要前往城市N,并允许她将不多于K条道路的距离变为0。文章提供了完整的C++代码实现。
563

被折叠的 条评论
为什么被折叠?



