很优雅的代码(把时间复杂度控到22)
2026-08-30 23:01:11
发布于:广东
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
struct Edge{
int u,v;
ll w,b;
}e[5005];
vector<pair<int,ll>> g[5005];
int n,m;
void spfa(vector<ll>& dis, const vector<int>& sources){
queue<int> q;
vector<bool> inq(n+1,false);
for(int x : sources){
if(!inq[x]){
q.push(x);
inq[x]=true;
}
}
while(!q.empty()){
int u = q.front(); q.pop();
inq[u]=false;
for(auto &pr : g[u]){
int to = pr.first;
ll w = pr.second;
if(dis[to] > dis[u] + w){
dis[to] = dis[u] + w;
if(!inq[to]){
inq[to]=true;
q.push(to);
}
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m;
for(int i=0;i<m;i++){
cin>>e[i].u>>e[i].v>>e[i].w>>e[i].b;
}
sort(e,e+m,[](const Edge&a,const Edge&b){return a.b < b.b;});
vector<ll> d1(n+1,INF);
vector<ll> dn(n+1,INF);
d1[1]=0;
dn[n]=0;
ll ans = INF;
int ptr=0;
while(ptr<m){
int curB = e[ptr].b;
int j=ptr;
vector<int> src;
while(j<m && e[j].b == curB){
int u=e[j].u, v=e[j].v; ll w=e[j].w;
g[u].emplace_back(v,w);
g[v].emplace_back(u,w);
src.push_back(u);
src.push_back(v);
j++;
}
spfa(d1, src);
spfa(dn, src);
for(int k=ptr;k<j;k++){
int u=e[k].u, v=e[k].v;
ll op1=INF,op2=INF;
if(d1[u]!=INF && dn[v]!=INF) op1 = d1[u]+dn[v];
if(d1[v]!=INF && dn[u]!=INF) op2 = d1[v]+dn[u];
ans = min(ans, min(op1,op2));
}
ptr=j;
}
if(ans>=INF) cout<<-1<<endl;
else cout<<ans<<endl;
return 0;
}
这里空空如也



有帮助,赞一个