sgu226


我写的SPFA最短路,似乎没有什么好说的。


时间复杂度: O(n2)


#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;       
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值