UVA 10000 Longest Paths(SPFA)

题意是让求最长路,和最短路思想一样
代码是套的kuangbin的SPFA的模板

#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

const int MAXN = 110;

struct Edge
{
    int v,cost;
    Edge(int _v = 0, int _cost = 0):v(_v),cost(_cost){}
};
vector<Edge> E[MAXN];

void addEdge(int u, int v, int w)
{
    E[u].push_back(Edge(v,w));
}

bool vis[MAXN];
bool cnt[MAXN];
int dist[MAXN];

bool SPFA(int start, int n)
{
    memset(cnt,0,sizeof(cnt));
    memset(vis,false,sizeof(vis));
    memset(dist,0,sizeof(dist));
    vis[start] = true;
    dist[start] = 0;
    queue<int> que;
    que.push(start);
    cnt[start] = 1;
    while(!que.empty())
    {
        int u = que.front();
        que.pop();
        vis[u] = false;
        for(int i = 0; i < E[u].size(); ++i)
        {
            int v = E[u][i].v;
            if(dist[v] < dist[u] + E[u][i].cost)
            {
                dist[v] = dist[u] + E[u][i].cost;
                if(!vis[v])
                {
                    vis[v] = true;
                    que.push(v);
                    if(++cnt[v] > n) return false;
                }
            }
        }
    }
    return true;
}

int main()
{
    int n,start,time = 0;
    while(cin >> n && n)
    {
        ++time;
        memset(E,0,sizeof(E));
        cin >> start;
        int u,v;
        while(cin >> u >> v && (u+v))
            addEdge(u,v,1);
        SPFA(start,n);
        int res = 0,ires = 0;
        for(int i = 1; i <= n; ++i)
        {
            if(dist[i] > res)
            {
                res = dist[i];
                ires = i;
            }
        }
        cout << "Case " << time << ": The longest path from " << start << " has length " << res << ", finishing at " << ires << "." << endl << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值