在图论里,最短路,次短路,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[