L. Magical Girl Haze

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

题目来源

ACM-ICPC 2018 南京赛区网络预赛

 

思路:网上有两种思路 ,大体出发点一样 ,因为K<=10,所以思想就是将原有图扩充为十层,第j层表示j次边化为零,跑一个spfa,自己笨啊~不会啊~难受啊~

 

代码:

#include
using namespace std;
typedef long long ll;
const int maxn=5e6+5;

struct edge{
    ll v,w,nex;
    edge(ll v=0,ll w=0,ll nex=0):v(v),w(w),nex(nex){}
}e[maxn];

ll p[maxn];
ll en;

void add(ll u,ll v,ll w){
    e[++en]=edge(v,w,p[u]);
    p[u]=en;
}

struct node{
    ll id,w;
    node(ll id,ll w):id(id),w(w){}

    bool operator <(const node &a)const{
        return w>a.w;
    }
};

bool vis[maxn];
long long dis[maxn];

void dij(){
    priority_queueq;
    memset(dis,0x3f3f3f3f,sizeof(dis));
    memset(vis,false,sizeof(vis));
    dis[1]=0;
    q.push(node(1,0));
    while(!q.empty()){
        node tmp=q.top();
        q.pop();
        long long id=tmp.id;
//        printf("%lld %lld \n",id,dis[id]);
        vis[id]=true;
        for(long long i=p[id];~i;i=e[i].nex){
            long long v=e[i].v;
            long long val=e[i].w;
            if(vis[v]) continue;
            if(dis[v]>dis[id]+val){
                dis[v]=dis[id]+val;
                q.push(node(v,dis[v]));
            }
        }
    }
}

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n,m,k;
        scanf("%d%d%d",&n,&m,&k);
        memset(p,-1,sizeof(p));
        en=-1;
        ll u,v,w;
        for(int i=1;i<=m;i++){
            scanf("%lld%lld%lld",&u,&v,&w);
            for(int j=0;j<=k;j++){
                add(u+n*j,v+n*j,w);
                if(j!=k) add(u+n*j,v+n*(j+1),0);
            }
        }
        dij();
        printf("%lld\n",dis[n*(k+1)]);
    }
}

 

你可能感兴趣的:(思路题,SPFA)