摸了快一个月的鱼我突然决定改过自新QwQ
单源最短路径....应该没人不知道
那么就用一道难度比模板大一些的题目来当例子吧
洛谷P1462 通往奥格瑞玛的道路
https://www.luogu.org/problemnew/show/P1462
看到“最大的最小”或者"最小的最大"时,基本可以确定是一道二分答案的题目了
#include<cstdio>
#include<queue>
#include<climits>
using namespace std;
inline int read(){
int f = 1,x = 0;
char c = getchar();
while(c>'9' || c<'0'){if(c == '-')f = -1;c = getchar();}
while(c<='9' && c>='0'){x = x*10 + c-'0';c = getchar();}
return x * f;
}
const int MAXN = 10005;
const int MAXM = 50005;
const int INF = INT_MAX;//正无穷
int hp,n,m,cost[MAXN],l = INF,r;
//边
struct Edge{
int next,to,v;
}edge[MAXM<<1];
int head[MAXN],ecnt;
void addedge(int from,int to,int v){
edge[++ecnt].next = head[from];
edge[ecnt].to = to;
edge[ecnt].v = v;
head[from] = ecnt;
}
//输入数据
void init(){
n = read();m = read();hp = read();
for(int i = 1;i <= n;i++){
cost[i] = read();
if(cost[i] > r)r = cost[i];
if(cost[i] < l)l = cost[i];
}
int a,b,c;
for(int i = 0;i < m;i++){
a = read();b = read();c = read();
if(a == b)continue;//注意题目中说的a可能等于b
addedge(a,b,c);
addedge(b,a,c);
}
}
//点
struct node{
int pos,d;
bool operator <(const node &x)const{
return d > x.d;
}
};
long long dist[MAXN];
bool dij(int x){
priority_queue<node> que;
for(int i = 1;i <= n;i++)dist[i] = INF;
dist[1] = 0;
que.push(node{1,0});
while(!que.empty()){
node temp = que.top();
que.pop();
int now = temp.pos;
int d = temp.d;
if(d != dist[now])continue;
for(int i = head[now];i;i = edge[i].next){
int to = edge[i].to;
int v = edge[i].v;
if(cost[to] > x)continue;//如果超过了上限就不走这个点
if(dist[to] > dist[now] + v){
dist[to] = dist[now] + v;
que.push(node{to,dist[to]});
}
}
}
return dist[n] <= hp;//判断这条路走完还活不活着
//因为是以血量为边权的最短路
//所以不用担心有别的更少掉血的选择
}
int main(){
init();
int ans;
if(!dij(r)){//注意要先判断是否为AFK
printf("AFK");
return 0;
}
while(l <= r){//二分答案
int mid = (l + r) >> 1;
if(dij(mid)){
ans = mid;
r = mid - 1 ;
}
else l = mid + 1;
}
printf("%d",ans);
return 0;
}