0蓝桥王国 - 蓝桥云课
问题描述
小明是蓝桥王国的王子,今天是他登基之日。
在即将成为国王之前,老国王给他出了道题,他想要考验小明是否有能力管理国家。
题目的内容如下:
蓝桥王国一共有 N 个建筑和 M 条单向道路,每条道路都连接着两个建筑,每个建筑都有自己编号,分别为 1∼N。(其中皇室的编号为1)
国王想让小明回答从皇宫到每个建筑的最短路径是多少,但紧张的小明此时已经无法思考,请你编写程序帮助小明回答国王的考核。
输入描述
输入第一行包含两个正整数 N,M。
第2到 M+1 行每行包含三个正整数 u,v,w,表示 u→v 之间存在一条距离为 w 的路。
1≤N≤3×105,1≤m≤106,1≤u,vi≤N,0≤wi≤109。
输出描述
输出仅一行,共 N 个数,分别表示从皇宫到编号为 1∼N 建筑的最短距离,两两之间用空格隔开。(如果无法到达则输出 -1)
输入输出样例
示例1
输入:
3 3
1 2 1
1 3 5
2 3 2
输出:
0 1 3
运行限制
- 最大运行时间:2s
- 最大运行内存:512M
思路:
模板没什么好说的
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll L = 1e6+10;
const ll P = 3e5+10;
ll N,M,tot;
ll head[P],dis[P];
bool vis[P];
typedef pair<ll,ll> PII;
struct Edge{
ll next,to,w;
}e[L];
void add(ll u,ll v,ll w)
{
++tot;
e[tot].next = head[u];
e[tot].to = v;
e[tot].w = w;
head[u] = tot;
}
void dij()
{
memset(dis,0x3f,sizeof dis);
priority_queue<PII,vector<PII>,greater<PII>> p;
dis[1] = 0;
p.push({dis[1],1});
while(!p.empty())
{
auto k = p.top();
p.pop();
ll d = k.first;
ll pos = k.second;
if(vis[pos])continue;
vis[pos] = true;
ll u = head[pos];
while(u != -1)
{
ll to = e[u].to;
ll w = e[u].w;
if(dis[to] > d + w)
{
dis[to] = d + w;
p.push({dis[to],to});
}
u = e[u].next;
}
}
for(ll i = 1 ; i <= N ; i++)
{
if(dis[i] == 0x3f3f3f3f3f3f3f3f)
{
cout << -1 << " ";
}
else
{
cout << dis[i] << " ";
}
}
}
int main(void)
{
cin >> N >> M;
for(ll i = 1 ; i <= N ; i++)
{
head[i] = -1;
}
for(ll i = 1 ; i <= M ; i++)
{
ll u,v,w;
cin >> u >> v >> w;
add(u,v,w);
}
dij();
return 0;
}