社区讨论
有木有大神帮我看看,第一点总是TLE
P3385【模板】负环参与者 3已保存回复 2
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 2 条
- 当前快照
- 1 份
- 快照标识符
- @mieafp6m
- 此快照首次捕获于
- 2025/11/25 16:02 3 个月前
- 此快照最后确认于
- 2025/11/25 16:55 3 个月前
第一个点总是TLE,AI也优化不明白,
有没有大神帮小白改改
CPP#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2005, M = 3005;
int T, n, m, to[M << 1], h[N], w[M << 1], ne[M << 1], idx;
int distances[N], updatecnt[N];
bool enter[N];
void add(int a, int b, int c) {
to[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx++;
}
void init() {
idx = 1;
memset(h, -1, sizeof h);
memset(distances, 0x3f3f3f3f, sizeof distances);
memset(enter, false, sizeof enter);
memset(updatecnt, 0, sizeof updatecnt);
}
bool spfa() {
int queue[N * 10000];
int l = 0, r = 0;
distances[1] = 0;
queue[r++] = 1;
enter[1] = true;
updatecnt[1]++;
while (l < r) {
int u = queue[l++];
enter[u] = false;
for (int ei = h[u]; ei != -1; ei = ne[ei]) {
int v = to[ei];
int c = w[ei];
if (distances[u] + c < distances[v]) {
distances[v] = distances[u] + c;
if (!enter[v]) {
if (++updatecnt[v] == n) {
return true;
}
queue[r++] = v;
enter[v] = true;
}
}
}
}
return false;
}
int main() {
ios::sync_with_stdio(0);
std::cin.tie(0);
std::cout.tie(0);
cin >> T;
while (T--) {
cin >> n >> m;
init();
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
if (c >= 0) {
add(a, b, c);
add(b, a, c);
}
else {
add(a, b, c);
}
}
if (spfa()) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
return 0;
}
回复
共 2 条回复,欢迎继续交流。
正在加载回复...