题意是让求最长路,和最短路思想一样
代码是套的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;
}