标签:att ring org thml lse math pac 距离 i++
给定一个n个点m条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你判断图中是否存在负权回路。
第一行包含整数n和m。
接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。
如果图中存在负权回路,则输出“Yes”,否则输出“No”。
1≤n≤20001≤n≤2000,
1≤m≤100001≤m≤10000,
图中涉及边长绝对值均不超过10000。
3 3
1 2 -1
2 3 4
3 1 -4
Yes
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N = 1e4 + 10;
int h[N],w[N],ne[N],e[N],idx;
int n,m;
bool st[N];
int d[N],cnt[N];//距离和边数
void add(int a,int b,int c){
e[idx] = b,w[idx] = c,ne[idx] = h[a],h[a] = idx ++;
}
int spfa(){
//不需要初始化距离,因为求的不是绝对值
queue<int> q;
for(int i = 1;i <= n;i++){//题目没有说从1开始
st[i] = true;//将所有的点集全部放在spfa队列的初始点集里边,这样只要存在负环一定可以找到
q.push(i);
}
while(q.size()){
int t = q.front();
q.pop();
st[t] = false;
for(int i = h[t];i != -1;i = ne[i]){
int j = e[i];
if(d[j] > d[t] + w[i]){
d[j] = d[t] + w[i];
cnt[t] = cnt[t] + 1;
if(cnt[t] >= n) return true;//n个边就存在n+1个点
if(!st[t]){
st[j] = true;
q.push(j);
}
}
}
}
return false;
}
int main(){
cin >> n >> m;
memset(h,-1,sizeof h);
for(int i = 0;i < m;i++){
int a,b,c;
cin >> a >> b >> c;
add(a,b,c);
}
if(spfa())cout <<"Yes";
else cout << "No";
return 0;
}
标签:att ring org thml lse math pac 距离 i++
原文地址:https://www.cnblogs.com/luyuan-chen/p/11838383.html