BZOJ4144 [AMPPZ2014]Petrol 【最短路 + 最小生成树】

题目链接

BZOJ4144

题解

这题好妙啊,,orz

假设我们在一个非加油站点,那么我们一定是从加油站过来的,我们剩余的油至少要减去这段距离

如果我们在一个非加油站点,如果我们到达不了任意加油站点,我们一定废了

那么我们在一个非加油站点,就一定可以到达最近的加油站,而由于我们剩余的油是要减去到加油站距离的,所以我们剩余的油一定是\(b - d\),\(d\)表示到达最近加油站的距离。假如我们没有那么多油,我们一定可以开过去再回来,就有了

因此,我们在任意一个点的油量确定,两点之间可以直达,当且仅当

①两点间有边

②\(w + d[u] + d[v] \le b\)

因此可以以此为新边权跑最小生成树,同时离线回答询问

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
using namespace std;
const int maxn = 200005,maxm = 400005,INF = 2000000026;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
return out * flag;
}
int n,s,m,Q,c[maxn];
int h[maxn],ne;
struct EDGE{int to,nxt,w;}ed[maxm];
inline void build(int u,int v,int w){
ed[++ne] = (EDGE){v,h[u],w}; h[u] = ne;
ed[++ne] = (EDGE){u,h[v],w}; h[v] = ne;
}
struct edge{int a,b,w;}e[maxn];
inline bool operator < (const edge& a,const edge& b){
return a.w < b.w;
}
struct Que{int u,v,b,id;}q[maxn];
inline bool operator < (const Que& a,const Que& b){
return a.b < b.b;
}
priority_queue<cp,vector<cp>,greater<cp> > qu;
int vis[maxn],d[maxn];
void dijkstra(){
for (int i = 1; i <= n; i++) d[i] = INF;
for (int i = 1; i <= s; i++)
d[c[i]] = 0,qu.push(mp(0,c[i]));
int u;
while (!qu.empty()){
u = qu.top().second; qu.pop();
if (vis[u]) continue;
vis[u] = true;
Redge(u) if (!vis[to = ed[k].to] && d[u] + ed[k].w < d[to]){
d[to] = d[u] + ed[k].w;
qu.push(mp(d[to],to));
}
}
}
int ans[maxn],pre[maxn];
inline int find(int u){return u == pre[u] ? u : pre[u] = find(pre[u]);}
void kruskal(){
REP(i,m) e[i].w = e[i].w + d[e[i].a] + d[e[i].b];
sort(e + 1,e + 1 + m);
int t = 1,fa,fb;
REP(i,n) pre[i] = i;
for (int i = 1; i <= m; i++){
while (t <= Q && e[i].w > q[t].b){
ans[q[t].id] = (find(q[t].u) == find(q[t].v));
t++;
}
fa = find(e[i].a); fb = find(e[i].b);
if (fa != fb) pre[fb] = fa;
}
while (t <= Q){
ans[q[t].id] = (find(q[t].u) == find(q[t].v));
t++;
}
}
int main(){
n = read(); s = read(); m = read();
REP(i,s) c[i] = read();
REP(i,m){
e[i].a = read(); e[i].b = read(); e[i].w = read();
build(e[i].a,e[i].b,e[i].w);
}
Q = read();
REP(i,Q) q[i].u = read(),q[i].v = read(),q[i].b = read(),q[i].id = i;
sort(q + 1,q + 1 + Q);
dijkstra();
kruskal();
REP(i,Q) puts(ans[i] ? "TAK" : "NIE");
return 0;
}
上一篇:js的实参是按值传递还是按引用传递


下一篇:【BZOJ4144】[AMPPZ2014]Petrol(最短路+最小生成树+并查集)