spfa最长路
#include<bits/stdc++.h>
using namespace std;
#define fo(i,x,y) for(int i=(x);i<=(y);i++)
#define fu(i,x,y) for(int i=(x);i>=(y);i--)
const int N=2e5+5;
int n,m;
int to[N*2],val[N*2],nxt[N*2],head[N],rp;
void add_edg(int x,int y,int z){
to[++rp]=y;
val[rp]=z;
nxt[rp]=head[x];
head[x]=rp;
}
int dis[N];
bool vis[N];
priority_queue<int> q;
void spfa(int s){
memset(dis,-1,sizeof(dis));
dis[s]=0;
q.push(s);vis[s]=true;
while(!q.empty()){
int x=q.top();q.pop();
vis[x]=false;
for(int i=head[x];i;i=nxt[i]){
int y=to[i];
if(dis[y]<dis[x]+val[i]){
dis[y]=dis[x]+val[i];
if(!vis[y])q.push(y),vis[y]=true;
}
}
}
}
signed main(){
scanf("%d%d",&n,&m);
fo(i,1,m){
int x,y,z;scanf("%d%d%d",&x,&y,&z);
add_edg(x,y,z);
}
spfa(1);
printf("%d",dis[n]);
}
堆优化dij
#include<bits/stdc++.h>
using namespace std;
#define fo(i,x,y) for(int i=(x);i<=(y);i++)
#define fu(i,x,y) for(int i=(x);i>=(y);i--)
const int N=2e5+5;
int n,m;
int to[N*2],val[N*2],nxt[N*2],head[N],rp;
void add_edg(int x,int y,int z){
to[++rp]=y;
val[rp]=z;
nxt[rp]=head[x];
head[x]=rp;
}
int dis[N];
bool vis[N];
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q;
void dij(int s){
memset(dis,0x3f,sizeof(dis));
memset(vis,false,sizeof(vis));
dis[s]=0;
q.push({dis[s],s});
while(!q.empty()){
pair<int,int> x=q.top();q.pop();
if(vis[x.second])continue;
vis[x.second]=true;
for(int i=head[x.second];i;i=nxt[i]){
int y=to[i];
if(dis[y]>dis[x.second]+val[i]){
dis[y]=dis[x.second]+val[i];
q.push({dis[y],y});
}
}
}
}
signed main(){
}
dijkstra图
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define fo(i,x,y) for(int i=(x);i<=(y);i++)
#define fu(i,x,y) for(int i=(x);i>=(y);i--)
const int N=3e5+5;
int n,m,dis[N],pre[N];
int to[N*2],val[N*2],nxt[N*2],head[N],rp;
void add_edg(int x,int y,int z){
to[++rp]=y;
val[rp]=z;
nxt[rp]=head[x];
head[x]=rp;
}
bool vis[N];
void dij(int s){
memset(dis,0x3f,sizeof(dis));
memset(pre,0,sizeof(pre));
memset(vis,false,sizeof(vis));
dis[s]=0;pre[s]=0;
fo(i,1,n){
int nw=0,mn=0x3f3f3f3f;
fo(j,1,n)if(!vis[j]&&dis[j]<mn)
mn=dis[j],nw=j;
vis[nw]=true;
for(int j=head[nw];j;j=nxt[j]){
int y=to[j];
if(vis[y])continue;
if(dis[y]>dis[nw]+val[j]){
dis[y]=dis[nw]+val[j];
pre[y]=nw;
}
}
}
}
signed main(){
}
THE END