萌新求助,只wa了一个点
查看原帖
萌新求助,只wa了一个点
322896
xixi_bang楼主2020/5/25 11:34
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<queue>
using namespace std;
const int M = 6e3 + 5;
const int N = 2e3 + 5;
int cnt = 0;
int dis[N];
int inq[N];
int coun[N];
int head[N];
int n, m;
struct E { int to, next, w; };
E edge[M];

void add_edge(int u, int v, int w) {
	cnt++;
	edge[cnt].to = v;
	edge[cnt].w = w;
	edge[cnt].next = head[u];
	head[u] = cnt;
}

int add(int a, int b) {
	if (a == 0x3f3f3f3f || b == 0x3f3f3f3f)
		return 0x3f3f3f3f;
	else return a + b;
}
void init() {
	cnt = 0;
	memset(dis, 0x3f, sizeof(dis));
	memset(inq, 0, sizeof(inq));
	memset(coun, 0, sizeof(coun));
	memset(head, 0, sizeof(head));
}
bool spfa() {
	queue<int> que;
	que.push(1);
	inq[1] = 1;
	dis[1] = 0;
	while (!que.empty()) {
		int t = que.front();
		que.pop();
		inq[t] = 0;
		for (int j = head[t]; j; j = edge[j].next) {
			int tot = edge[j].to;
			if (dis[tot] >add( dis[t] , edge[j].w)) {
				dis[tot] = add(dis[t], edge[j].w);
				coun[tot]++;
				if (coun[tot] >= n) return true;//存在负环
				if (!inq[tot]) {
					inq[tot] = 1;
					que.push(tot);
				}
			}
		}
	}
	return false;

}
int main() {
	//freopen("K:\Opera默认下载位置\P3385_9.in","r",stdin);
	//freopen("K:\Opera默认下载位置\P3385_9.myout", "w",stdout);
	int t;
	cin >> t;
	while (t--) {
		cin >> n >> m;
		init();
		for (int i = 1; i <= m; i++) {
			int u, v, w;
			cin >> u >> v >> w;
			add_edge(u, v, w);
			if (w > 0) add_edge(v, u, w);
		}
		if (spfa()) cout << "YES" << endl;
		else cout << "NO" << endl;
	}

}
2020/5/25 11:34
加载中...