P1119 灾后重建 题解
wisdom2010 · · 题解
前言
本题解使用 Djikstra + 堆优化,时间复杂度接近于
题意
题目传送门 >>
有
解法
首先看到题目的第一眼就想到可以用
只是一个普通的堆优化
注意
不使用堆优化的
代码
#include<bits/stdc++.h>
using namespace std;
int n, m;
const int maxn = 2e2 + 10;
int t[maxn];
struct line
{
int v, w;
bool operator < (const line& a) const {
return w > a.w;
}
};
vector<line> a[maxn];
int q;
bool vis[maxn];
int dis[maxn];
priority_queue<line> p;
void dijstra(int x, int y, int tm)
{
memset(dis, 0x3f, sizeof(dis));
memset(vis, false, sizeof(vis));
p.push({x, 0});
dis[x] = 0;
while(!p.empty())
{
line now = p.top();
p.pop();
int u = now.v;
if(vis[u])
continue;
vis[u] = true;
for(auto it : a[u])
{
int v = it.v;
int w = it.w;
if(t[v] > tm)
continue;
if(dis[v] > dis[u] + w)
{
dis[v] = dis[u] + w;
p.push({v, dis[v]});
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for(int i = 0; i <= n - 1; i++)
cin >> t[i];
for(int i = 1; i <= m; i++)
{
int u, v, w;
cin >> u >> v >> w;
a[u].push_back({v, w});
a[v].push_back({u, w});
}
cin >> q;
while(q--)
{
int x, y, tm;
cin >> x >> y >> tm;
if(t[x] > tm || t[y] > tm)
{
cout << -1 << "\n";
continue;
}
dijstra(x, y, tm);
if(dis[y] == 0x3f3f3f3f)
cout << -1 << "\n";
else
cout << dis[y] << "\n";
}
return 0;
}
在输入查询的时候,可以通过判断当前的两个村庄
注意在最后输出的时候如果当前的
书写不易,不喜勿喷~