题目链接:

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=499

题意:就是推断图中有无负环

SPFA,某个节点入队次数大于n就是有负环。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <string>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <malloc.h> using namespace std; const int MAXN = 41000;
const int INF = 0x3f3f3f3f; struct Edge
{
int v;
int cost;
Edge(int _v = 0, int _cost = 0)
{
v = _v;
cost = _cost;
}
};
vector<Edge> E[MAXN]; void addedge(int u, int v, int cost)
{
E[u].push_back(Edge(v, cost));
} bool vis[MAXN];
int cnt[MAXN];//记录入队列的次数
int dist[MAXN]; ////////////////
bool SPFA(int start, int n)
{
memset(vis, false, sizeof(vis));
memset(cnt, 0, sizeof(cnt));
for (int i = 0; i <= n; i++) dist[i] = INF;
vis[start] = true;
dist[start] = 0;
queue<int> que;
while (!que.empty()) que.pop();
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);
cnt[v]++;
if (cnt[v] > n) return false;
}
}
}
}
return true;
} int n, m;
int a, b, c; int main()
{
int t;
scanf("%d",&t);
while (t--)
{
scanf("%d%d",&n,&m);
for (int i = 0; i <= n; i++) E[i].clear();
while (m--)
{
scanf("%d%d%d", &a, &b, &c);
addedge(a, b, c);
//addedge(b, a, c);
}
if (!SPFA(0, n)) puts("possible");
else puts("not possible");
}
return 0;
}

最新文章

  1. 创建NetWorkDataset---FileGDB篇
  2. Linux环境下Nginx配置安装PHP
  3. Scalaz(31)- Free :自由数据结构-算式和算法的关注分离
  4. 解决Django发送中文邮件时的编码及乱码问题
  5. (一)WebRTC手记之初探
  6. python数据采集与多线程效率分析
  7. Android Studio NDK 学习之接受Java传入的Int数组
  8. 在竞赛ACM Java处理输入输出
  9. Appium绑定
  10. 多线程程序设计学习(6)Producer-Consumer模式
  11. python 文件查找 glob
  12. shell if判断(曾经被一个字符串相等的判断纠结半小时,最后只是if后少了个空格!) 和 awk引用外部变量判断
  13. Modelsim覆盖率
  14. Codeforces 67C Sequence of Balls 编辑距离 dp
  15. HDU 4333 Revolving Digits 扩展KMP
  16. javascript入门视频第一天 小案例制作 零基础开始学习javascript
  17. vue的配置环境篇
  18. 如何使用iOS开发者授权以及如何申请证书
  19. [20190227]简单探究tab$的bojb#字段.txt
  20. QTP键盘操作笔记

热门文章

  1. Android Shape使用
  2. Linux安装PHP和MySQL
  3. 30.algorithm排序小结
  4. html页面全屏化显示
  5. Flume 启动
  6. append生成新变量的时候,没有如预期(It's a feature,not a bug?)
  7. PostgreSQL Replication之第三章 理解即时恢复(3)
  8. Linux VNC Viewer客户端
  9. POJ-2785 Values whose Sum is 0 Hash表
  10. CF209C Trails and Glades(欧拉路)