1. 程式人生 > >POJ 2449 Remmarguts' Date 第K短路 A* + dij

POJ 2449 Remmarguts' Date 第K短路 A* + dij

A*/第k短路模板題

#include <iostream>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <map>
#include <algorithm>
#include <queue>
#include <set>
#include <cmath>
#include <sstream>
#include <stack>
#include <fstream>
#include <functional>
#pragma warning(disable:4996);
#define mem(sx,sy) memset(sx,sy,sizeof(sx))
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-8;
const double PI = acos(-1.0);
const ll llINF = 0x3f3f3f3f3f3f3f3f;
const int INF = 0x3f3f3f3f;
using namespace std;
#define pli pair<ll, int>
const int maxn = 1005;
const int maxm = 100005;
//const int mod = 1e9 + 7;
struct edge {
	int from, to, next;
	ll w;
};
struct Dij {
	edge edges[maxm];
	int n, cnt1;
	int head[maxn];
	int vis[maxn];
	ll dist[maxn];

	void init(int _n) {
		n = _n;
		mem(head, -1);
		mem(vis, 0);
		cnt1 = 0;
	}

	void addedge(int u, int v, int w) {
		edges[++cnt1].from = u;
		edges[cnt1].to = v;
		edges[cnt1].w = w;
		edges[cnt1].next = head[u];
		head[u] = cnt1;
	}

	void dij(int s) {
		mem(dist, llINF);
		priority_queue<pli, vector<pli>, greater<pli> > Q;
		Q.push(pli(0, s));
		dist[s] = 0;
		while (!Q.empty()) {
			int u = Q.top().second; Q.pop();
			vis[u] = 1;
			for (int i = head[u]; i != -1; i = edges[i].next) {
				int v = edges[i].to;
				ll w = edges[i].w;
				if (dist[v] > dist[u] + w && !vis[v]) {
					dist[v] = dist[u] + w;
					Q.push(pli(dist[v], v));
				}
			}
		}
	}
}GR;

struct A {
	int f, g, v;
	A(int _g = 0, int _f = 0, int _v = 0)
		:g(_g), f(_f), v(_v) {}
	bool operator <(const A a)const {
		if (a.f == f) return a.g < g;
		return a.f < f;
	}
};
struct Astar {
	edge edges[maxm];
	int n, cnt1;
	int head[maxn];
	int vis[maxn];
	ll dist[maxn];

	void init(int _n) {
		n = _n;
		mem(head, -1);
		cnt1 = 0;
	}

	void addedge(int u, int v, int w) {
		edges[++cnt1].from = u;
		edges[cnt1].to = v;
		edges[cnt1].w = w;
		edges[cnt1].next = head[u];
		head[u] = cnt1;
	}

	ll astar(int s, int e, int k) {
		priority_queue<A> Q;
		if (s == e)k++;
		if (GR.dist[s] == llINF) return -1;
		int cnt = 0;
		Q.push(A(0, GR.dist[s], s));
		while (!Q.empty()) {
			A tmp = Q.top(); Q.pop();
			int u = tmp.v;
			if (u == e) {
				++cnt;
			}
			if (cnt == k)return tmp.g;
			for (int i = head[u]; i != -1; i = edges[i].next) {
				int v = edges[i].to;
				int w = edges[i].w;
				Q.push(A(tmp.g + w, tmp.g + w + GR.dist[v], v));
			}
		}
		return -1;
	}
}G1;

int main() {
	int n, m;
	while (~scanf("%d%d", &n, &m)) {
		GR.init(n);
		G1.init(n);
		for (int i = 0, u, v, w; i < m; i++) {
			scanf("%d%d%d", &u, &v, &w);
			GR.addedge(v, u, w);
			G1.addedge(u, v, w);
		}
		int s, e, k;
		scanf("%d%d%d", &s, &e, &k);
		GR.dij(e);
		printf("%lld\n", G1.astar(s, e, k));
	}
}