ICPC2018南京网络赛 Magical Girl Haze(分层图+优先队列优化spfa)

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 ***
{
	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;
}

 

全部评论

相关推荐

美团 后端开发 总包n(15%是股票)
点赞 评论 收藏
分享
喜欢吃蛋糕仰泳鲈鱼是我的神:字节可以找个hr 给你挂了,再放池子捞
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务