图论的各种姿势(上)

一、最短路:

1.Floyd

int V, E;
int d[MAX_V][MAX_V];

void Floyd-Warshall()
{
	for(int k = 1; k <= V; k+ +)
		for(int i = 1; i <= V; i ++)
			for(int j = 1; j <= V; j ++)
				d[i][j] = min(d[i][j],d[i][k] + d[k][j]);
}


2.Dijkstra

<pre name="code" class="cpp">struct zt{
	int u, v;
	bool operator < (const zt&b)const
	{
		return v > b.v;
	}
};

priority_queue<zt> q; 
void dijkstra(int s)
{
	d[s] = 0;
	q.push((zt){s,0});
	while(!q.empty())
	{
		zt x = q.top();
		q.pop();
		int u = x.u ;
		done[u] = 1;
		for(int i = first[u]; i != -1; i = next[i]) 
		{
			int v = es[i].to ;
			if(d[v] > d[u] + es[i].cost )
			{
				d[v] = d[u] + es[i].cost ;
				q.push((zt){v,d[v]}); 
			}
		}
	}
}


 3.Bellman_Ford 

int V, E;
int d[233333];

struct edge{
	int from, to, cost;
};
edge es[23333];

void Bellman_Ford(int s)
{
	 
	for(int i = 1;i <= V;i ++)
		d[i] = 0x7fffffff;
	d[s] = 0;
	while(true)
	{
		bool bh = 0;  
		for(int i = 1; i <= E;i ++) 
		{
			edge e=es[i];
			if(d[e.from] != 0x7fffffff && d[e.to] > d[e.from] + e.cost){
				d[e.to] = d[e.from] + e.cost;
				bh = 1;  
			}
		}
		if(!bh) break;
	}
}

进化——SPFA!

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 10000 + 5 ;
int n,m,a,b,c,xw,tot;
int first[maxn],next[maxn<<1],d[maxn<<2];
bool used[maxn],vis;
struct edge{
	int from,to,cost;
}es[maxn<<1];

void build(int f,int t,int d)
{
	es[++tot]=(edge){f,t,d};
	next[tot]=first[f];
	first[f]=tot;
}

queue<int>q;
void spfa(int s)
{
	d[s]=0;
	q.push(s);
	used[s]=1;
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		used[u]=0;
		for(int i=first[u];i!=-1;i=next[i])
		{
			int v=es[i].to;
			if(d[v]>d[u]+es[i].cost)
			{	
				d[v]=d[u]+es[i].cost;
			
				if(!used[v])
				{
					q.push(v);
					used[v]=1;
				}
			}
		}
	}
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值