跳到正文

闲话

2025.1.16の收获

linzeyu2012约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年1月16日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 5 分钟
获赞
2

版本

  1. v1当前

今日收获:

1.学会了SPFA算法

2.知道了各种最短路算法适合的图的类型

3.学会了负环的判定方法

4.学会了Bellman–Ford算法

今日代码:

C++
//#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;
				}
			}
		}
	}
}
C++
//#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";
}
C++
//#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);	
			}
		}
	}
}
C++
//#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

原文