题解:AT_abc481_d [ABC481D] Autopilot
题目传送门
题意:
给定
-
免费移动:飞到当前星球能到达的所有星球中,编号最小的那个星球。
-
消耗燃料移动:花费
1 单位燃料,飞到任意一个当前星球能到达的星球。
求从起点 -1。
分析:
常规的 BFS 或者 Dijkstra 很难直接处理“免费去最小的”这种带特殊条件的移动。但是,我们可以换个角度思考:能不能把这种“特殊移动”转化成图上的“特殊边权”?
我们可以把所有航线看成有向边,对每条边赋予
- 对于星球
u ,如果我们走的是通往编号最小星球的那条边,我们不需要消耗燃料,边权为0 。 - 如果我们走的是通往其他星球的边,我们需要消耗
1 单位燃料,边权为1 。
这样一来,题目就转化成了:在一个边权只有
因为边权只有
思路:
-
存图:用邻接表
vector<node> e[N]存图。在存图的同时,记录每个星球u 连出去的最小星球编号mn[u],初始化为INF。 -
更新边权:存完图后,遍历每一个星球
u 的所有出边。如果出边指向的星球x.to等于\text{mn}_u ,说明这是免费移动,把这条边的边权x.w改为0 ;否则保持为1 。 -
Dijkstra:
- 初始化
dist数组为极大值,dist[s] = 0。 - 将起点
S 放入优先队列。 - 每次取出当前代价最小的节点
u ,遍历其所有的出边。如果通过u 走到v 的代价更小,则更新dist[v]并将其入队。
- 初始化
-
输出答案:如果
dist[t]依然是极大值,说明无法到达,输出-1;否则输出dist[t]。
复杂度分析:
- 时间复杂度:
O(M \log N) 。由于每个节点和每条边最多被处理一次,优先队列的插入和弹出操作总代价为O(M \log N) ,完全可以通过N, M \le 2 \times 10^5 的数据。
赛时AC记录:
AC代码:
#include<bits/stdc++.h>
#define int long long
#define rep(c,l,r) for (int c=l;c<=r;c++)
using namespace std;
const int N=200005;
struct node{
int to,w;
};
vector<node> e[N]; //邻接表存图
int mn[N],dist[N]; //mn记录能到达的最小编号,dist记录最短代价
struct node2{ //优先队列的结构体,重载小于号,使代价小的优先出队
int u,cst;
bool operator<(const node2& st) const{
return cst>st.cst;
}
};
int dijkstra(int n,int s,int t){ //dijkstra
rep(i,1,n){
dist[i]=1e18; //初始化
}
dist[s]=0;
priority_queue<node2> pq;
pq.push({s,0});
while(!pq.empty()){
node2 cur=pq.top();
pq.pop();
int u=cur.u,cst=cur.cst;
if(cst>dist[u]){ //如果当前取出的代价已经大于记录的最短路,直接跳过
continue;
}
for(auto x:e[u]){ //遍历所有出边
int v=x.to,w=x.w;
if(dist[u]+w<dist[v]){
dist[v]=dist[u]+w;
pq.push({v,dist[v]});
}
}
}
if(dist[t]==1e18){
return -1;
}
return dist[t];
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,m,s,t;
cin>>n>>m>>s>>t;
rep(i,1,n){
mn[i]=1e18; //初始化mn
}
rep(i,1,m){
int u,v;
cin>>u>>v;
mn[u]=min(mn[u],v); //维护该点能到达的最小星球
node x;
x.to=v,x.w=1;
e[u].push_back(x);
}
rep(i,1,n){ //将通往最小星球的边权改为0
for(auto &x:e[i]){
if(x.to==mn[i]){
x.w=0;
}
}
}
cout<<dijkstra(n,s,t); //dijkstra求最短路
return 0;
}