P1462 通往奥格瑞玛的道路
思路:
先看一下题干理解一下啊,我们要求的结果是经过的所有城市中最多的一次收取的费用的最小值是多少。,懂么?反正我不懂😂😂😂,好吧,在仔细审题(瞪眼大法)之后,其实就是在保证主人公血量补呗扣完的情况下,所走的路上城市最多,且收取的最大的费用最小。那么我们的思路也就呼之欲出了啊,对于每个城市收取的费用进行二分答案再对没一次的二分答案进行判断,如果消耗的生命值大于我们的hp那么就返回
f
a
l
s
e
false
false。
有两种二分的方法,首先是正常的对消费数组二分:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<cstdio>
#include<cmath>
#include<iomanip>
#include<queue>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
typedef pair<int, int> pii;
const int N = 4e5 + 10;
ll e[N], ne[N], h[N], idx,w[N],f[N],u[N];
ll n, m, d;
void add(int x, int y, ll z) {
e[idx] = y, ne[idx] = h[x], w[idx] = z, h[x] = idx++;
}
ll dis[N];
bool st[N];
bool spfa(int x) {
for (int i = 0; i <= n; i++)dis[i] = 0x3f3f3f3f, st[i] = false;
dis[1] = 0;
st[1] = true;
queue<int>q;
q.push(1);
while (q.size()) {
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (dis[j] > dis[t] + w[i]&&u[j] <= x) {
dis[j] = dis[t] + w[i];
if (!st[j]) {
q.push(j);
st[j] = true;
}
}
}
}
if (dis[n] > d)return false;
return true;
}
int main() {
cin >> n >> m >> d;
for (int i = 0; i <= n; i++)h[i] = -1;
int l = 1, r = n;
for (int i = 1; i <= n; i++) {
cin >> u[i];
f[i] = u[i];//这里要注意,用两个数组因为下面要排序,而spfa中做判断时不用排序。
}
for (int i = 1; i <= m; i++) {
int a, b, c;
cin >> a >> b >> c ;
add(a, b, c);
add(b, a, c);
}
sort(f + 1, f + 1 + n);
int mid = 0;
if (!spfa(f[n])) {
puts("AFK");
}
else {
while (l < r)
{
mid = l + r >> 1;
if (spfa(f[mid]))r = mid;
else l = mid + 1;
}
cout << f[r] << endl;
}
}
第二种就是对 1 1 1 − - − m a x f [ i ] maxf[i] maxf[i] 进行二分答案。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<cstdio>
#include<cmath>
#include<iomanip>
#include<queue>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
typedef pair<int, int> pii;
const int N = 4e5 + 10;
ll e[N], ne[N], h[N], idx,w[N],f[N];
ll n, m, d;
void add(int x, int y, ll z) {
e[idx] = y, ne[idx] = h[x], w[idx] = z, h[x] = idx++;
}
ll dis[N];
bool st[N];
bool spfa(int x) {
for (int i = 0; i <= n; i++)dis[i] = 0x3f3f3f3f, st[i] = false;
dis[1] = 0;
st[1] = true;
queue<int>q;
q.push(1);
while (q.size()) {
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (dis[j] > dis[t] + w[i]&&f[j] <= x) {
dis[j] = dis[t] + w[i];
if (!st[j]) {
q.push(j);
st[j] = true;
}
}
}
}
if (dis[n] > d)return false;
return true;
}
int main() {
cin >> n >> m >> d;
for (int i = 0; i <= n; i++)h[i] = -1;
int l = 1, r = 0;
for (int i = 1; i <= n; i++) {
int h;
cin >> h;
f[i] = h;
r = max(r, h);
}
for (int i = 1; i <= m; i++) {
int a, b, c;
cin >> a >> b >> c ;
add(a, b, c);
add(b, a, c);
}
int mid = 0;
if (!spfa(1e9 + 10)) {
puts("AFK");
}
else {
while (l < r)
{
mid = l + r >> 1;
if (spfa(mid))r = mid;
else l = mid + 1;
}
cout << l << endl;
}
}