Floyd
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]);
Dijkstra
void dij(int e)
{
for(int i=1;i<=n;i++)dis[i]=E[e][i];
for(int i=1;i^n;i++)
{
int min=oo,u;
for(int j=1;j<=n;j++)
{
if(!vis[j] and dis[j]<min)
min=dis[u=j];
}
vis[u]=1;
for(int v=1;v<=n;v++)
{
if(!vis[v] and dis[v]>dis[u]+E[u][v])
dis[v]=dis[u]+E[u][v];
}
}
}
邻接链表
struct E{int next,to,w;};
E edge[N];
int head[N]->-1,cnt->1;
void add(int u,int v,int w)
{
edge[cnt].next=head[u];
edge[cnt].w=w;
edge[cnt].to=v;
head[u]=cnt++;
}
for(int i=head[k];~i;i=edge[i].next)
Dij(priority_queue)
struct E{int v,w;};
bool operator <(E a,E b){return a.w>b.w;}
vector<E>g[N];
int vis[N]->0,dis[N]->oo;
void dij(int s)
{
priority_queue<E>dp;
dis[s]=0;
dp.push((E){s,0});
while(!dp,empty())
{
E node=dp.top();
dp.pop();
int u=node.v;
if(vis[u])continue;
vis[u]=1;
for(E e:g[u])
{
if(!vis[e.v] and dis[e.v]>dis[u]+e.w)
{
dis[e.v]=dis[u]+e.w;
dp.push((E){e.v,dis[e.v]});
}
}
}
}
Spfa
struct node
{
int to,next,v;
}Edge[N];
int head[N],dis[N],tot;
void add_edge(int a,int b,int c)
{
Edge[++tot].to=b;
Edge[tot].v=c;
Edge[tot].next=head[a];
head[a]=tot;
}
bool spfs(int s,int n)
{
queue<int>q;
int num[N],vis[N],k,to,v;
memset(num,0,sizeof(num));
memset(vis,0,sizeof(vis));
dis[s]=0;
q.push(s);
vis[s]=1;
while(!q.empty())
{
k=q.front();
q.pop();
vis[k]=0;
for(int i=head[k];i!=-1;i=Edge[i].next)
{
to=Edge[i].to;
v=Edge[i].v;
if(dis[k]+v<dis[to])
{
dis[to]=dis[k]+v;
if(!vis[to])
{
vis[to]=1;
q.push(to);
num[to]++;
if(num[to]>n)return false;
}
}
}
}
return true;
}
dij(set)
struct edge{int to,length;};
vector<edge>graph[N];
int n;
int min_distance[N];
int dij(int source){
min_distance[source]=0;
set<pair<int,int> >g;
g.insert({0,source});
while(!g.empty()){
int where=g.begin()->second;
g.erase(g.begin());
for(auto &e:graph[where]){
if(min_distance[e.to]>min_distance[where]+e.length){
g.erase({min_distance[e.to],e.to});
min_distance[e.to]=min_distance[where]+e.length;
g.insert({min_distance[e.to],e.to});
}
}
}
}
©著作权归作者所有:来自51CTO博客作者qinXpeng的原创作品,如需转载,请注明出处,否则将追究法律责任
共同学习,写下你的评论
评论加载中...
作者其他优质文章