飞船超越虫洞

#include<iostream>
#include<vector>
#include<list>
#include<string>
#include<queue>
using namespace std;

struct state
{
	int node_id;
	int m_energy;

	state(int id, int energy) :node_id(id), m_energy(energy) {}
};

bool cmp(state& S1, state& S2)
{
	return S1.m_energy < S2.m_energy;
}


class Solution
{
public:
	void min_energy()
	{

		auto res = Dijstra();

		for (size_t i = 1; i < res.size(); i++)
		{
			cout << i <<' '<< res[i] << endl;
		}

	}
	void Create_graph() 
	{
		cin >> Node_num;
		G = vector<list<pair<int,int>>>(Node_num+1);
		cin.get();

		char ch = ' ';
		while (ch!='\n')
		{
			string flag;
			getline(cin, flag);

			if (!flag.empty() )
			{
				int start = (int)flag[2] - 48;
				int end = (int)flag[0] - 48;
				int weight;
				if (flag[4]=='t')
				{
					weight = 1;
				}
				else
				{
					weight = 0;
				}
				G[start].push_back(make_pair(end,weight));
				start_node_id = (int)flag[2] - 48;
			}
			else
			{
				ch = '\n';
			}
		}

	}

private:

	vector<list<pair<int,int>>> G;
	int Node_num;
	int start_node_id;

	vector<int> Dijstra()
	{

		vector<int> max_energy(Node_num, -1);
		priority_queue<state, vector<state>, decltype(&cmp)> pq(cmp); //大顶堆

		state start_node(start_node_id, 0);
		max_energy[start_node_id] = 0;

		pq.push(start_node);

		while (!pq.empty())
		{
			state cur_node = pq.top();
			pq.pop();

			int cur_node_id = cur_node.node_id;
			int cur_node_energy = cur_node.m_energy;

			if (cur_node.m_energy<max_energy[cur_node_id])
			{
				continue;
			}
			for (auto pair_: G[cur_node_id])
			{
				int weight = pair_.second;
				int next_node_id = pair_.first;
				int next_energy = cur_node.m_energy+weight;

				if (next_energy>max_energy[next_node_id])
				{
					max_energy[next_node_id] = next_energy;
					state next_node(next_node_id, next_energy);
					pq.push(next_node);
				}
			}
		}

		return max_energy;
	}


};


int main()
{
	auto* s = new Solution;

	s->Create_graph();
	s->min_energy();

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值