【图论算法】 最短路,次短路,k短路总结

在图论里,最短路,次短路,k短路的问题很常见。
这里总结一下。

存图技巧

数据小,稠密图的一般用邻接矩阵
稀疏图,数据大一般用邻接表(vector,链式前向星都可)

邻接矩阵

const int maxn = 1e5+5;
int Graph[maxn][maxn];	// 正权图可以初始化成-1来判断是否连通,负权图可以再考虑开个数组或者用一个很大的值。

链式前向星

const int maxn = 1e5+5;
struct Edge{
   
		int u,v,nxt;
}edge[maxn];
int head[maxn],tot;
inline void addedge(int u,int v,int w){
   	// u->v 权值是w
		edge[++tot] = {
   u,v,w};
		head[u] = tot;
}

最短路

一般最短路算法有 BFS(暴力,一般只适用于点数小的情况),dijiastra(解决正权图),spfa(解决负权图,但容易死,被卡),floyed(解决点与点之间的最短距离问题,dp)

这里直接给出单源最短路的算法(因为都挺好理解的) (重点在于松弛操作!)

dijiastra

// 堆优化版本
const int maxn = 1e5+5;
struct Edge{
   
    int u,v,nxt,w;
}edge[maxn];
int head[maxn],tot;
inline void init(){
   
    memset(head,-1,sizeof(head));
}
inline void addedge(int u,int v,int w){
   
    edge[++tot] = {
   u,v,head[u],w};
    head[u] = tot;
}
int dis[maxn];  bool vis[maxn];
inline void dijiastra(int s){
   
    struct Node{
   
        int u,dis;
        bool operator <(const Node &h)const{
   
            return dis > h.dis;
        }
    };
    memset(dis,0x3f,sizeof(dis));   //  视具体情况而定初始化的值
    dis[s] = 0;
    priority_queue<Node> pq;    pq.push(Node{
   s,0});
    while(!pq.empty()){
   
        Node u = pq.top();  pq.pop();
        if(vis[u.u])    continue;
        vis[u.u] = true;
        for(int i = head[
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值