Magical Girl Haze

There are NNN cities in the country, and MMM directional roads from uuu to v(1≤u,v≤n)v(1\le u, v\le n)v(1≤u,v≤n). Every road has a distance cic_ici​. Haze is a Magical Girl that lives in City 111, she can choose no more than KKK roads and make their distances become 000. Now she wants to go to City NNN, please help her calculate the minimum distance.

Input

The first line has one integer T(1≤T≤5)T(1 \le T\le 5)T(1≤T≤5), then following TTT cases.

For each test case, the first line has three integers N,MN, MN,M and KKK.

Then the following MMM lines each line has three integers, describe a road, Ui,Vi,CiU_i, V_i, C_iUi​,Vi​,Ci​. There might be multiple edges between uuu and vvv.

It is guaranteed that N≤100000,M≤200000,K≤10N \le 100000, M \le 200000, K \le 10N≤100000,M≤200000,K≤10,
0≤Ci≤1e90 \le C_i \le 1e90≤Ci​≤1e9. There is at least one path between City 111 and City NNN.

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+优先队列。

代码:

#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <queue>
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f

using namespace std;

typedef pair<int,int> p;

struct node
{
    int u,v,w,next;
}h[5000000];

struct node1
{
    int s,k;
}m,n;

int head[100200];
int a,b,c,t;
int vis[100200][12];
long long int dis[100200][12];

void addre(int u, int v,int w)
{
    h[t].u=u;
    h[t].v=v;
    h[t].w=w;
    h[t].next=head[u];
    head[u]=t++;
}

void spfa()
{
    priority_queue<p,vector<p>,greater<p> > Q;
    memset(dis,inf,sizeof(dis));
    Q.push(make_pair(1,0));
    dis[1][0]=0;
    while(Q.size())
    {
        p now=Q.top();
        Q.pop();
        n.s=now.first;
        n.k=now.second;
        int i;
        for(i=head[n.s];i!=-1;i=h[i].next)
        {
            if(dis[h[i].v][n.k]>dis[n.s][n.k]+h[i].w)
            {
                dis[h[i].v][n.k]=dis[n.s][n.k]+h[i].w;
                    Q.push(make_pair(h[i].v,n.k));
            }
            if(n.k+1<=c)
            {
                if(dis[h[i].v][n.k+1]>dis[n.s][n.k])
                {
                    dis[h[i].v][n.k+1]=dis[n.s][n.k];
                    Q.push(make_pair(h[i].v,n.k+1));
                }
            }
        }

    }
}

int main()
{
    int i,j;
    int u,v,w;
    scanf("%d",&j);
    while(j--){
    scanf("%d %d %d",&a,&b,&c);
    t=0;
    memset(head,-1,sizeof(head));
    for(i=1;i<=b;i++)
    {
        scanf("%d %d %d",&u,&v,&w);
        addre(u,v,w);
    }
    spfa();
    printf("%lld\n",dis[a][c]);
    }
    return 0;
}
扫描二维码关注公众号,回复: 3187671 查看本文章

猜你喜欢

转载自blog.csdn.net/The_city_of_the__sky/article/details/82595058