今日收获:
1.学会了SPFA算法
2.知道了各种最短路算法适合的图的类型
3.学会了负环的判定方法
4.学会了Bellman–Ford算法
今日代码:
//#1:SPFA
ll n,m,s;
struct node{
ll v,w;
}newnode;
vector<node> e[10050];
ll dis[10050];
bool inqueue[10050];
void spfa(){
for(int i=1;i<=10050;i++) dis[i]=2147483647;
queue<ll> q;
q.push(s);
inqueue[s]=true;
dis[s]=0;
while(!q.empty()){
ll h=q.front();
q.pop();
inqueue[h]=false;
for(node i:e[h]){
ll v=i.v;
ll w=i.w;
if(dis[v]>dis[h]+w){
dis[v]=dis[h]+w;
if(!inqueue[v]){
q.push(v);
inqueue[v]=1;
}
}
}
}
}//#2:判断负环
struct node{
ll v,w;
}newnode;
vector<node> e[100050];
ll dis[100050];
bool inqueue[100050];
int cnt[100050];
void spfa(){
queue<ll> q,Q;
q=Q;
q.push(1);
inqueue[1]=true;
dis[1]=0;
cnt[1]++;
while(!q.empty()){
ll h=q.front();
q.pop();
inqueue[h]=false;
for(node i:e[h]){
ll v=i.v;
ll w=i.w;
if(dis[v]>dis[h]+w){
dis[v]=dis[h]+w;
if(!inqueue[v]){
inqueue[v]=1;
q.push(v);
cnt[v]++;
if(cnt[v]>n){
cout<<"YES\n";
return;
}
}
}
}
}
cout<<"NO\n";
}//#3:Dijkstra
struct side{
ll to,len;
}sd;
vector<side> e[N];
ll dis[M];
struct node{
ll id,d;
}nd;
bool operator<(node a,node b){
return a.d>b.d;
}
priority_queue<node>q;
ll n,m,s;
void dij(ll s){
memset(dis,0x3f,sizeof(dis));
dis[s]=0;
nd={s,0};
q.push(nd);
while(!q.empty()){
ll h=q.top().id;
ll d=q.top().d;
q.pop();
if(d!=dis[h]) continue;
for(ll i=0;i<e[h].size();i++){
ll to=e[h][i].to,len=e[h][i].len;
if(dis[to]>dis[h]+len){
dis[to]=dis[h]+len;
nd.id=to;
nd.d=dis[to];
q.push(nd);
}
}
}
}//#4:Bellman–Ford
struct Edge {
int u, v, w;
};
vector<Edge> edge;
int dis[MAXN], u, v, w;
constexpr int INF = 0x3f3f3f3f;
bool bellmanford(int n, int s) {
memset(dis, 0x3f, (n + 1) * sizeof(int));
dis[s] = 0;
bool flag = false;
for (int i = 1; i <= n; i++) {
flag = false;
for (int j = 0; j < edge.size(); j++) {
u = edge[j].u, v = edge[j].v, w = edge[j].w;
if (dis[u] == INF) continue;
if (dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
flag = true;
}
}
if (!flag) {
break;
}
}
return flag;
}END