struct Spfa:Graph{ int d[maxn],inq[maxn]; void short_path(int s,int*dist){ for(int i=0;i<=n;i++) dist[i]=1e9; dist[s]=0; deque<int>q; q.push_back(s); inq[s]=1; long long sum=0; while(!q.empty()){ int u=q.front(); q.pop_front(); sum-=dist[u];inq[u]=0; if(1ll*dist[u]*q.size()>sum){//large label last sum+=dist[u]; q.push_back(u); inq[u]=1; } else{ for(int i=head[u];~i;i=edge[i].nex){ int v=edge[i].v, w=edge[i].w; if(dist[v]>dist[u]+w){ if(inq[v]){ sum-=dist[v]; dist[v]=dist[u]+w; sum+=dist[v]; } else{ dist[v]=dist[u]+w; inq[v]=1; sum+=dist[v]; if(dist[v]<dist[q.front()]) q.push_front(v);//small lable first else q.push_back(v); } } } } } } }g;
struct Dijkstra:Graph{ int d[maxn]; struct dijnode{ int d,u; bool operator<(const dijnode&rhs)const{return d>rhs.d;} dijnode(int d,int u):d(d),u(u){} }; void short_path(int s,int*dist){//short path for(int i=0;i<=n;i++) dist[i]=1e9; priority_queue<dijnode>q;// dis and vert dist[s]=0; q.push(dijnode(dist[s],s)); while(!q.empty()){ int u = q.top().u; q.pop(); for(int i=head[u];~i;i=edge[i].nex){ int v=edge[i].v, w=edge[i].w; if(dist[u]+w<dist[v]){ dist[v]=dist[u]+w; q.push(dijnode(dist[v],v)); } } } } };
const int maxn=1e6; int buf[maxn]; struct graph{ static const int maxn=1e3+5; static const int maxm=1e5+5; struct star{ int v,w,nex; star(int v=0,int w=0,int nex=0):v(v),w(w),nex(nex){} }edge[maxm];//有向图不要双倍边 int head[maxn], tot, n; void init(int _n){ n=_n; tot=-1; memset(head,-1,(n+1)*sizeof(head[0])); } void add_edge(int u,int v,int w){ edge[++tot]=star(v,w,head[u]); head[u]=tot; } struct dijnode{ int d,u; bool operator<(const dijnode&rhs)const{return d>rhs.d;} dijnode(int d,int u):d(d),u(u){} }; void short_path(int s,int*dist){//short path for(int i=0;i<=n;i++) dist[i]=2e9; priority_queue<dijnode>q;// dis and vert dist[s]=0; q.push(dijnode(dist[s],s)); while(!q.empty()){ int u = q.top().u; q.pop(); for(int i=head[u];~i;i=edge[i].nex){ int v=edge[i].v, w=edge[i].w; if(dist[u]+w<dist[v]){ dist[v]=dist[u]+w; q.push(dijnode(dist[v],v)); } } } } struct Astarnode{ int d,need,u; bool operator<(const Astarnode&rhs)const{return d+need>rhs.d+rhs.need;} Astarnode(int d,int need,int u):d(d),need(need),u(u){} }; int kthway(graph&rev,int s,int t,int k){//from s to t the kth way , g是反向图 if(s==t)k++; int*dist=buf;//分配内存 rev.short_path(t,dist); if(dist[s]==2e9)return -1;//此路不通 priority_queue<Astarnode>q; q.push(Astarnode(0,dist[s],s)); while(!q.empty()){ int u = q.top().u, d=q.top().d; q.pop(); if(u==t){ k--; if(k==0)return d; } for(int i=head[u];~i;i=edge[i].nex){ int v=edge[i].v, w=edge[i].w; q.push(Astarnode(d+w,dist[v],v)); } } return -1;//没那么多路 } };