跳到正文

题解

AT_abc191_e [ABC191E] Come Back Quickly题解

elpsconr约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年10月31日
收录
2026年6月25日
更新
2026年11月11日
篇幅
约 4 分钟

版本

  1. v1当前

问题陈述:

在AtCoder共和国,有 NN个城镇编号为11至NN;有 MM条道路,编号为 11 至 MM 。道路 ii 是从Ai A_i镇到 Bi B_i 镇的单行道,经过需要 Ci C_i分钟。可能是 Ai A_i=Bi B_i,也可能有多条道路连接同一对城镇。对于每个城镇,确定是否存在以该城镇为起点的有效散步(即起点到终点可达)。此外,如果答案是肯定的,请找出这样一次散步所需的最短时间。

题解:

由题意得求起点到终点且起点等于终点的最短路,只要建一个分层图跑一遍djikstra即可,也就是求u到u+n的最短路,便可以避免索引重复,由于n很小,故可以采取暴力

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define PII pair<int,int>
#define tul tuple<int,int,int>
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define rep_(i,a,b) for(int i=a;i>=b;--i)
#define all(x) x.begin(),x.end()
#define bp(x) __builtin_popcountll(x)
#define ctz(x) __builtin_ctz(x)
#define cy cout<<"Yes"<<endl
#define cn cout<<"No"<<endl
#define lc (rt<<1)
#define rc (rt<<1|1)
mt19937_64 rnd(time(0));
const int N=3e5+5,yyx=1e9+7;
vector<PII> to[N];
int n,m;
inline int mod(int x){
  return (x%yyx+yyx)%yyx;
}
inline int cmin(int &x,int y){
  return x>y?x=y,1:0;
}
inline int cmax(int &x,int y){
  return x<y?x=y,1:0;
}
void djikstra(int x,vector<int> &d){
   vector<int> st(2*n+1,0);
   d.resize(2*n+1,2e14);
   d[x]=0;
   priority_queue<PII,vector<PII>,greater<PII> > q;
   q.push({0,x});
   while(q.size()){
    auto [xx,yy]=q.top();q.pop();
    if(st[yy]) continue;
    st[yy]=1;
    for(auto [v,w]:to[yy]){
        if(cmin(d[v],d[yy]+w)) q.push({d[v],v});
    }
   }
}
inline void solve(){
  cin>>n>>m;
  map<int,int> mp;
  rep(i,1,m){
    int u,v,w;cin>>u>>v>>w;
    to[u].push_back({v+n,w});
    to[u+n].push_back({v+n,w});
  }
  rep(i,1,n){
    vector<int> d;
    djikstra(i,d);
    if(d[i+n]==2e14) d[i+n]=-1;
    cout<<d[i+n]<<endl;
  }
}
signed main(){
  cin.tie(0)->sync_with_stdio(0);
  //freopen("D://321//in.txt","r",stdin);
  //freopen("D://321//out.txt","w",stdout);
  int _=1;
  //cin>>_;
  while(_--)
  solve();
  return 0;
}
原文