QOJ.ac

QOJ

Time Limit: 2 s Memory Limit: 512 MB Total points: 100

#7991. 最小环

统计

题目描述

小 I 发明了 $O(n + m)$ 的有向图最小环,于是他想考考你。

给定一个 $n$ 个节点、$m$ 条边的有向图,每条边有正整数边权。你需要求出图上的一个环使得环上边的边权和最小。求出这个最小值,或者报告不存在环。

当然,由于你不会 $O(n + m)$ 的有向图最小环,于是小 I 放宽了条件:保证输入的图是弱连通的,且 $m-n$ 不会很大。一个图是弱连通的当且仅当将有向边换为无向边后图连通。

输入格式

从标准输入读入数据。

第一行两个整数 $n,m (1 \le n \le 3 \times 10^5, -1 \le m-n \le 1500)$,表示图的点数和边数。

接下来 $m$ 行每行三个整数 $u_i,v_i,w_i (1 \le u_i,v_i \le n, 1 \le w_i \le 10^9)$,表示一条从 $u_i$ 到 $v_i$、边权为 $w_i$ 的有向边。保证图是弱连通的。

输出格式

输出到标准输出。

如果图中不存在环,输出 -1,否则输出一个整数表示最小环的长度和。

样例

输入

4 6
1 2 1
4 3 3
4 1 9
2 4 1
3 1 2
3 2 6

输出

7

解释

最小环为 $1 \to 2 \to 4 \to 3 \to 1$。

样例

输入

1 0

输出

-1

样例

输入

1 1
1 1 1

输出

1

解释

最小环为 $1 \to 1$。

About Issues

We understand that our problem archive is not perfect. If you find any issues with the problem, including the statement, scoring configuration, time/memory limits, test cases, etc.

You may use this form to submit an issue regarding the problem. A problem moderator will review your issue and proceed it properly.

STOP! Before you submit an issue, please READ the following guidelines:

  1. This is not a place to publish a discussion, editorial, or requests to debug your code. Your issue will only be visible by you and problem moderators. Other users will not be able to view or reply your issues.
  2. Do not submit duplicated issues. If you have already submitted one, please wait for an moderator to review it. Submitting multiple issues will not speed up the review process and might cause your account to be banned.
  3. Issues must be filed in English or Chinese only.
  4. Be sure your issue is related to this problem. If you need to submit an issue regarding another problem, contest, category, etc., you should submit it to the corresponding page.

Active Issues 0

No issues in this category.

Closed/Resolved Issues 0

No issues in this category.