sgu226 分类: sgu 2015-06-15 23:54 21人阅读 评论(0) 收藏
我写的SPFA最短路,似乎没有什么好说的。
时间复杂度:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
const int maxn = 205, INF = 0x3f3f3f3f, Nya = -1;
int n, m;
bool w[maxn][maxn][3];
int dist[maxn][3];
bool hash[maxn][3];
std::queue<int> line[3];
int SPFA()
{
memset(dist,INF,sizeof(dist));
memset(dist[1],0,sizeof(dist[1]));
memset(hash[1],true,sizeof(hash[1]));
for(int i = 0; i < 3; i++)
line[i].push(1);
while(true)
{
int opt = 0, node = 0;
for(int i = 0; i < 3; i++)
if(!line[i].empty())
{
int t = line[i].front();
if(dist[t][i] < dist[node][opt])
node = t, opt = i;
}
if(!node) break;
line[opt].pop(), hash[node][opt] = false;
for(int i = 0; i < 3; i++)
{
if(opt == i) continue;
for(int j = 1; j <= n; j++)
if(w[node][j][i] && dist[node][opt] + 1 < dist[j][i])
{
dist[j][i] = dist[node][opt] + 1;
if(!hash[j][i])
line[i].push(j), hash[j][i] = true;
}
}
}
int ans = INF;
for(int i = 0; i < 3; i++)
ans = std::min(ans, dist[n][i]);
return (ans < INF)? ans: -1;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("sgu226.in","r",stdin);
freopen("sgu226.out","w",stdout);
#endif
std::cin >> n >> m;
for(int i = 1, u, v, c; i <= m; i++)
{
std::cin >> u >> v >> c;
w[u][v][c-1] = true;
}
std::cout << SPFA();
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。