POJ.2387 Til the Cows Come Home (SPFA)

时间:2021-08-28 16:21:40

POJ.2387 Til the Cows Come Home (SPFA)

题意分析

  1. 首先给出T和N,T代表边的数量,N代表图中点的数量
  2. 图中边是双向边,并不清楚是否有重边,我按有重边写的。
  3. 直接跑spfa,dij,floyd都可以。
  4. 求1到N的最短路。

代码总览

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#define nmax 1005
#define inf 1e8+7
using namespace std; int mp[nmax][nmax];
int n,m;
int shortdis[nmax];
void spfa(int s)
{
bool isinqueue[nmax];
queue<int> q;
while(!q.empty()) q.pop();
int now = s;
memset(isinqueue,0,sizeof(isinqueue));
for(int i = 1;i<=n;++i) shortdis[i] = inf;
shortdis[s] = 0;
q.push(s);
isinqueue[s] = true;
while(!q.empty()){
now = q.front(); q.pop();
isinqueue[now] = false;
for(int i = 1;i<=n;++i){
if(i != now && mp[now][i] + shortdis[now] < shortdis[i]){
q.push(i);
isinqueue[i] = true;
shortdis[i] = shortdis[now] + mp[now][i];
}
}
}
}
int main()
{
while(scanf("%d %d",&m,&n) != EOF){
for(int i = 1 ;i<=n;++i)
for(int j = 1;j<=n;++j)
mp[i][j] = inf;
for(int i = 1;i<=m;++i){
int x,y,dis;
scanf("%d %d %d",&x,&y,&dis);
int temp = mp[x][y];
if(dis<temp){
mp[x][y] = mp[y][x] = dis;
}
}
spfa(1);
printf("%d\n",shortdis[n]);
}
return 0;
}