就是运用bellman-ford算法,关键在于理解题意。
Input
Line 1: A single integer, F. F farm descriptions follow.
Line 1 of each farm: Three space-separated integers respectively: N, M, and W
Lines 2..M+1 of each farm: Three space-separated numbers (S, E, T) that describe, respectively: a bidirectional path between S and E that requires T seconds to traverse. Two fields might be connected by more than one path.
Lines M+2..M+W+1 of each farm: Three space-separated numbers (S, E, T) that describe, respectively: A one way path from S to E that also moves the traveler back T seconds.
大概题意:
John有F个农场,每个农场有若干个点(1<=N<=500),每两个点可以用paths连接(双向,权值为正),也可以用wormholes来连接(单向,权值为负),求是否有一个负权值回路。
#include<iostream>
#include<fstream>
using namespace std;
#define EDGE_MAX 2702
#define TIME_MAX 10001
int dist[502];
int n, m, w;
int all_edges;
struct EDGE{
int s;
int e;
int t;
}edges[5*EDGE_MAX];
bool fellman_ford()
{
memset(dist, TIME_MAX, sizeof(dist));
bool flag = false;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < all_edges; j++)
{
if (dist[edges[j].e] > dist[edges[j].s]+edges[j].t)
{
dist[edges[j].e] = dist[edges[j].s] + edges[j].t;
flag = true;
}
}
if (!flag)
break;
}
for (int k = 0; k < all_edges; k++)
{
if (dist[edges[k].e]>dist[edges[k].s] + edges[k].t)
return true;
}
return false;
}
int main()
{
int num,ss,ee,tt;
//ifstream in("text.txt");
cin >> num;
for (int i = 0; i < num; i++)
{
cin >> n >> m >> w;
all_edges = 0;
for (int j = 0; j < m; j++)
{
cin >> ss >> ee >> tt;
edges[all_edges].s = ss;
edges[all_edges].e = ee;
edges[all_edges++].t = tt;
edges[all_edges].s = ee;
edges[all_edges].e = ss;
edges[all_edges++].t = tt;
}
for (int k = 0; k < w; k++)
{
cin >> ss >> ee >> tt;
edges[all_edges].s = ss;
edges[all_edges].e = ee;
edges[all_edges++].t = -tt;
}
if (fellman_ford())
cout << "YES" << endl;
else
cout << "NO" << endl;
}
//system("pause");
return 0;
}