dijsktra(mlogn)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int N,M,S,T;
struct Edge
{
int u,v,w;
};
struct Node
{
int w,u;
Node(int _w,int _u):w(_w),u(_u){}
bool operator <(constNode &other) const
{
return w>other.w;
}
};
Edge edges[1005];
vector<int> G[205];
priority_queue<Node> PQ;
bool vis[205];
#define INF 0X7FFFFFFF
int d[205];
int main()
{
while (scanf("%d %d",&N,&M)!=EOF)
{
for (int i=0; i<205; i++)
G[i].clear();
while (!PQ.empty())
PQ.pop();
memset(vis,false, sizeof(vis));
for (int i=0; i<M; i++)
{
scanf("%d %d %d",&edges[i].u,&edges[i].v,&edges[i].w);
//添加以u邻接的边序号
G[edges[i].u].push_back(i);
G[edges[i].v].push_back(i);
}
//dijkstra nlogn
int ans=-1;
scanf("%d %d",&S,&T);
for (int i=0; i<N; i++)
d[i]=INF;
d[S]=0;
PQ.push(Node(0,S));
while (!PQ.empty())
{
Node topNode=PQ.top();
PQ.pop();
//结点序号
int u=topNode.u;
if (vis[u])
continue;
vis[u]=true;
if (u==T)
{
ans=topNode.w;
break;
}
for (int i=0; i<G[u].size(); i++)
{
//对与u邻接的边作松弛操作
Edge &e=edges[G[u][i]];
//确定当前边的起点和终点
int from=e.u==u?u:e.v;
int to=e.u==u?e.v:e.u;
if (d[to]>d[from]+e.w)
{
d[to]=d[from]+e.w;
PQ.push(Node(d[to],to));
}
}
}
printf("%d\n",ans);
}
}
bellmanford
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int N,M,S,T;
struct Edge
{
int u,v,w;
};
Edge edges[1005];
vector<int> G[205];
queue<int> Q;
bool inq[205];
#define INF 0X7FFFFFFF
int d[205];
int main()
{
while (scanf("%d %d",&N,&M)!=EOF)
{
for (int i=0; i<205; i++)
G[i].clear();
memset(inq, false, sizeof(inq));
for (int i=0; i<M; i++)
{
scanf("%d %d %d",&edges[i].u,&edges[i].v,&edges[i].w);
//添加以u邻接的边序号
G[edges[i].u].push_back(i);
G[edges[i].v].push_back(i);
}
//dijkstra nlogn
int ans=-1;
scanf("%d %d",&S,&T);
for (int i=0; i<N; i++)
d[i]=INF;
d[S]=0;
Q.push(S);
while (!Q.empty())
{
int u=Q.front();
Q.pop();
inq[u]=false;
for (int i=0; i<G[u].size(); i++)
{
//对与u邻接的边作松弛操作
Edge &e=edges[G[u][i]];
//确定当前边的起点和终点
int from=e.u==u?u:e.v;
int to=e.u==u?e.v:e.u;
if (d[to]>d[from]+e.w)
{
d[to]=d[from]+e.w;
Q.push(to);
inq[to]=true;
}
}
}
if (d[T]!=INF)
printf("%d\n",d[T]);
else
printf("-1\n");
}
}