社区讨论

样例能过,其他全错,求调

P3385【模板】负环参与者 2已保存回复 1

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
1 条
当前快照
1 份
快照标识符
@mhjakfvi
此快照首次捕获于
2025/11/03 23:25
4 个月前
此快照最后确认于
2025/11/03 23:25
4 个月前
查看原帖
样例能过,其他全错,也不知道为什么 第一次学,都是照着模版写的 求求大佬调一下看看,谢谢
CPP
#include <bits/stdc++.h>
using namespace std;

const int N = 3005;
int T, n, m;
int e[N], ne[N], w[N], h[N], idx;
int cnt[N], dis[N];
bool st[N];

void add(int a, int b, int c) {
	e[idx] = b;
	ne[idx] = h[a];
	w[idx] = c;
	h[a] = idx++;
}

void init() {
	memset(dis, 0x3f, sizeof dis);
	memset(st, 0, sizeof st);
	memset(cnt, 0, sizeof cnt);
	memset(e, 0, sizeof e);
	memset(ne, 0, sizeof ne);
	memset(w, 0, sizeof w);
	idx = 0;
}

bool spfa()
{
    queue<int> q;

    for (int i = 1; i <= n; i ++ )
    {
        st[i] = true;
        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 (dis[j] > dis[t] + w[i])
            {
                dis[j] = dis[t] + w[i];
                cnt[j] = cnt[t] + 1;

                if (cnt[j] >= n) return true;
                if (!st[j])
                {
                    q.push(j);
                    st[j] = true;
                }
            }
        }
    }

    return false;
}


int main() {
	ios::sync_with_stdio(0);
	std::cin.tie(0);
	cin >> T;
	while (T--) {
		cin >> n >> m;
		memset(h, -1, sizeof h);
		init();
		for (int i = 0; i < m; i++) {
			int a, b, c;
			cin >> a >> b >> c;
			add(a, b, c);
		}
		if (spfa()) cout << "YES" << endl;
		else cout << "NO" << endl;
	} 
	return 0;
}

回复

1 条回复,欢迎继续交流。

正在加载回复...