#P3385. 【模板】负环

【模板】负环

Description

Given a directed graph with nn vertices, determine whether there exists a negative cycle that is reachable from vertex 11.

A negative cycle is defined as a cycle whose sum of edge weights is negative.

Input Format

This problem contains multiple groups of testdata in a single test point.

The first line contains an integer TT, representing the number of groups of testdata. For each group, the format is as follows:

The first line contains two integers, the number of vertices nn and the number of lines mm of edge information that follow.

Then follow mm lines, each with three integers u,v,wu, v, w.

  • If w0w \geq 0, then there exists an edge from uu to vv with weight ww, and also an edge from vv to uu with weight ww.
  • If w<0w < 0, then there exists only an edge from uu to vv with weight ww.

Output Format

For each group of testdata, output one line containing a string. Print YES if such a negative cycle exists, otherwise print NO.

2
3 4
1 2 2
1 3 4
2 3 1
3 1 -3
3 3
1 2 3
2 3 4
3 1 -8

NO
YES

Hint

Constraints and Conventions

For all test points, it is guaranteed that:

  • 1n2×1031 \leq n \leq 2 \times 10^3, 1m3×1031 \leq m \leq 3 \times 10^3.
  • 1u,vn1 \leq u, v \leq n, 104w104-10^4 \leq w \leq 10^4.
  • 1T101 \leq T \leq 10.

Hint

Please note that mm is not the number of edges of the graph.

Translated by ChatGPT 5