图的第k短路

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44316314/article/details/101800443
/*
启发式搜索求图的第k短路
f[i] = g[i] + h[i]
g[i]为到i点当前的花费,h[i]为到终点的最小花费
f[i]为评估从起点出发到终点的花费
每次取出f[i]最小的点进行bfs
到达终点第k次的就是答案 
*/ 
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
#define INF 0x3f3f3f3f

struct node{
	int num,val;
	node(int a,int b)
	{
		num = a;
		val = b;
	}
	bool operator<(const node&n)const
	{
		return val > n.val;
	}
};

struct f{
	int num,g,h;
	f(int a,int b,int c)
	{
		num = a;
		g = b;
		h = c;
	}
	bool operator<(const f&F) const
	{
		return g + h > F.g + F.h; 
	}
}; 

vector<node> g[1005];
vector<node> rg[1005];
int dist[1005];
int vis[1005];

void dij(int begin)
{
	priority_queue<node> q;
	dist[begin] = 0;
	q.push(node(begin,0));
	while( !q.empty() )
	{
		int x = q.top().num;
		q.pop();
		if( vis[x] ) continue;
		vis[x] = 1;
		for (int i = 0; i < rg[x].size(); i++)
		{
			node t = rg[x][i];
			if( !vis[t.num] && dist[t.num] > dist[x] + t.val )
			{
				dist[t.num] = dist[x] + t.val;
				t.val = dist[t.num];
				q.push(t); 
			}
		}
	} 
}

int k_shortPath(int x,int k,int e)
{
	int cnt = 0; 
	if( x == e ) k ++;
	if( dist[x] == INF ) return INF;
	priority_queue<f> q;
	q.push(f(x,0,dist[x]));
	while( !q.empty() )
	{
		f t = q.top();
		q.pop();
		if( t.num == e ) 
		{
			cnt ++; 
			if( cnt == k ) return t.g;
		}
		for (int i = 0 ; i < g[t.num].size(); i++)
		{
			node z = g[t.num][i];
			q.push(f(z.num,t.g+z.val,dist[z.num])); 
		}
	} 
	return -1;
}

int main()
{
	ios::sync_with_stdio(false);
    cin.tie(0);
	int n,m;
	while( cin >> n >> m )
	{
		memset(vis,0,sizeof(vis));
		for (int i = 1; i <= n; i++)
		{
			dist[i] = INF;
			g[i].clear();
			rg[i].clear();
		}
		int s,e,k,t;
		cin >> s >> e >> k >> t;
		for (int i = 0; i < m; i++)
		{
			int x,y,v;
			cin >> x >> y >> v;
			g[x].push_back(node(y,v));
			rg[y].push_back(node(x,v));  
		}
		dij(e);
		int res = k_shortPath(s,k,e);
		if( res <= t ) cout << "yareyaredawa" << endl;
		else cout << "Whitesnake!" << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44316314/article/details/101800443
今日推荐