L3-011 直捣黄龙 (30 分) dikstra算法

 解释都在代码里

板子大家做好记一下

dikstra主要用了贪心的思想

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N=1e3;
const int INF=0x3f3f3f3f;
map<string,int> mp;
int peo[N];
string a[N];
int n,k;//顶点个数 边的数目 
string s,e;//起到、终点 
vector<PII> E[N];//领接表 
bool vis[N];
int dis[N];//某一个点与起点的距离 
int path[N]; 
int cnt[N];//杀敌数目 
int num[N];//解放城镇数目 
int choice[N];//最短路径的条数 
void dikstra()//几乎全是板子 
{
	for(int i=0;i<=n;i++)
	{
	dis[i]=INF;
	path[i]=-1;
	vis[i]=false;
	}
	priority_queue<PII,vector<PII>,greater<PII> > q;//优先队列 
	dis[1]=0;
	q.push({0,1});
	//dis放前面,因为要找与七点距离最小的点,而优先队列排序是先按照first排 
	while(!q.empty())
	{
		int u=q.top().second;//结点 
		q.pop();
		if(vis[u]) continue;
		vis[u]=true;
		for(int i=0,l=E[u].size();i<l;i++)
		{
			int v=E[u][i].first,w=E[u][i].second;
			if(vis[v]) continue;
			if(dis[v]>dis[u]+w)
			{
				dis[v]=dis[u]+w;
				q.push({dis[v],v});
				cnt[v]=cnt[u]+peo[v];//总杀敌数
				path[v]=u;
				num[v]=num[u]+1;
				choice[v]=choice[u];
			}
			else if(dis[v]==dis[u]+w)
			{
				choice[v]+=choice[u];
				if(num[v]<num[u]+1)
				{
				num[v]=num[u]+1;
				path[v]=u;
				cnt[v]=cnt[u]+peo[v];
				}
				else if(num[u]+1==num[v]&&cnt[path[v]]<cnt[u])
				{
					path[v]=u;
					cnt[v]=cnt[u]+peo[v];
				}
			}
		}
	}
}
void print(int node)
{
	if(path[node]==-1) 
	{
	cout<<a[node];
	return;
	}
	else print(path[node]);
	cout<<"->"<<a[node];
}
int main()
{
	cin>>n>>k;
	cin>>s>>e;
	mp[s]=1;
	a[1]=s;
	choice[1]=1;
	string str;
	for(int i=2;i<=n;i++)
	{
		cin>>str;
		mp[str]=i;
		a[i]=str;
		cin>>peo[i];
	}
	for(int i=0;i<k;i++)
	{
		string s1,s2;
		cin>>s1>>s2;
		int w;
		cin>>w;
		E[mp[s1]].push_back({mp[s2],w});
		E[mp[s2]].push_back({mp[s1],w});//注意是个无向图,被坑了 
	}
	dikstra();
	print(mp[e]);
	printf("\n");
	cout<<choice[mp[e]]<<" "<<dis[mp[e]]<<" "<<cnt[mp[e]];
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值