分層圖

分層圖模板

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int N = 1e4 + 10;
const ll inf = (ll)1e16;
int x, y, z, st, ed;
vector <pii> V[N];
int n, m, k;
bool vis[N][12];
ll dis[N][12];

struct Node {
	int id, step;
	ll d;
	Node() {}
	Node(int id, int step, ll d):id(id),step(step),d(d) {}
	bool operator < (const Node &A)const {
		return d > A.d;
	}
};

void dijkstra(int st) {
	for(int i=1; i<=n; i++) 
		for(int j=0; j<=k; j++)
			dis[i][j] = inf, vis[i][j] = 0;;

	dis[st][0] = 0;
	priority_queue<Node> Q;
	Q.push(Node(st, 0, 0));
	Node nd;

	while(!Q.empty()) {
		nd = Q.top();
		Q.pop();
		if(nd.id == ed) break;
		if(vis[nd.id][nd.step]) continue;
		vis[nd.id][nd.step] = true;
		
		for(int i=0; i<V[nd.id].size(); i++) {
			int j = V[nd.id][i].first;
			int len = V[nd.id][i].second;
			int step = nd.step;
			if(dis[nd.id][step] + len < dis[j][step]){
				dis[j][step] = dis[nd.id][step] + len;
				Q.push(Node(j, step, dis[j][step]));
			}
			if(step == k) continue;
			if(dis[nd.id][step] < dis[j][step+1]){
				dis[j][step+1] = dis[nd.id][step];
				Q.push(Node(j, step+1, dis[j][step+1]));
			}
		}
	}
}

int main() {
	scanf("%d%d%d", &n, &m, &k);
	scanf("%d%d", &st, &ed);
	st++, ed++;
	for(int i=1; i<=n; i++) V[i].clear();
	while(m--) {
		scanf("%d%d%d", &x, &y, &z);
		x++, y++;
		V[x].push_back(make_pair(y, z));
		V[y].push_back(make_pair(x, z));
	}
	dijkstra(st);
	ll ans = inf;
	for(int i=0; i<=k; i++) ans = min(ans, dis[ed][i]);
	printf("%lld\n", ans);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章