您的位置:首页 > 其它

poj3259:spfa解法

2015-10-09 16:36 393 查看

构建一个队列,将松弛成功且不在队列的点放入队列,每次出队一个点.直到队列为空,如果队列中的某个入队次数超过n次,就说明存在一个负环.

#include "vector"
#include "queue"
#include "iostream"
using namespace std;
const double inf = 10000000;
struct node
{
int end;
double time_cost;
};
typedef vector<double> D;
bool relax(int beg,int end,double cost, D &distance)
{
if (distance[beg] + cost < distance[end])
{
distance[end] = distance[beg] + cost;
return true;
}
return false;
}
bool spfa(int N,D&distance, vector<vector<node>>& head)
{
queue<int> Q;
vector<int> isinq(N+1, 0);
vector<int> visited(N + 1, 0);
distance[0] = 0;
Q.push(0);
isinq[0] = 1;
while (!Q.empty())
{
int beg = Q.front();
Q.pop();
isinq[beg] = 0;//不在队列中
for (auto it : head[beg])
{
if (relax(beg, it.end, it.time_cost, distance))
{
if (!isinq[it.end])
{
Q.push(it.end);
isinq[it.end] = 1;
if (++visited[it.end] > N)
return true;
}
}
}
}
return false;
}
int main()
{
int F, N, M, W;
cin >> F;
while (F--)
{
cin >> N >> M >> W;
vector<vector<node>> head(N + 1);//N+1个点
int S, E;
double T;
while (M--)//普通path
{
cin >> S >> E >> T;
head[S].push_back({ E, T });
head[E].push_back({ S, T });
}
while (W--)//虫洞 one_way
{
cin >> S >> E >> T;
head[S].push_back({ E, -T });
}
int count = N;
while (count--)
head[0].push_back({count+1,0});

//初始化
auto it = head.begin();
bool ispossible = false;
D distance(N+1,inf);
ispossible = spfa(N,distance,head);
if (ispossible)
cout << "YES" << endl;
else
cout << "NO"<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: