对每一条边的两个邻接点a和b,从a->b的最小权值环为这条边的权值w+b到a的最小权值(通过Dijkstra求出),题目的点和边最多只有2000个,对每个边都跑一次dij也不会Tle。跑完之后如果存在环的话,那么顺着最短路更新答案。
// #pragma GCC optimize(2)
// #include <random>
// #include <windows.h>
// #include <ctime>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <set>
#include <map>
#define IO \
ios::sync_with_stdio(false); \
// cout.tie(0);
#define lson(x) node << 1, start, mid
#define rson(x) node << 1 | 1, mid + 1, end
using namespace std;
// int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
typedef unsigned long long ULL;
typedef long long LL;
typedef pair<int, int> P;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const int maxn = 2e3 + 10;
const int maxm = 1e2 + 10;
const LL mod = 1e9 + 7;
const double eps = 1e-8;
const double pi = acos(-1);
// int dis[4][2] = {1, 0, 0, -1, 0, 1, -1, 0};
// int m[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
struct Edge
{
int next, to, w;
} e[maxn << 1];
struct Node
{
int dot, val;
Node() {}
Node(int a, int b)
{
dot = a, val = b;
}
};
struct node
{
int a, b, c;
};
vector<node> v;
int head[maxn], ans[maxn], dis[maxn], pre[maxn];
int n, m, k;
bool vis[maxn];
void add(int u, int v, int w)
{
e[k].next = head[u];
e[k].to = v;
e[k].w = w;
head[u] = k++;
}
struct cmp
{
bool operator()(const Node a, Node b)
{
return a.val > b.val;
}
};
void Dijkstra(int s, int t, int c)
{
memset(dis, inf, sizeof dis);
memset(vis, false, sizeof vis);
// memset(pre, 0, sizeof pre);
priority_queue<Node, vector<Node>, cmp> q;
dis[s] = 0;
pre[s] = -1;
q.push(Node(s, 0));
while (!q.empty())
{
Node now = q.top();
q.pop();
int u = now.dot;
if (vis[u] == true)
continue;
vis[u] = false;
for (int i = head[u]; ~i; i = e[i].next)
{
int v = e[i].to;
if (dis[u] + e[i].w < dis[v])
{
pre[v] = u;
dis[v] = dis[u] + e[i].w;
q.push(Node(v, dis[v]));
}
}
}
int temp = dis[t] + c;
if (dis[t] == inf)
return;
else
{
while (t != -1)
{
// cout << t << " ";
ans[t] = min(temp, ans[t]);
t = pre[t];
}
return;
}
}
int main()
{
#ifdef WXY
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
IO;
int a, b, c;
node t;
cin >> n >> m;
memset(head, -1, sizeof head);
memset(ans, inf, sizeof ans);
for (int i = 0; i < m; i++)
{
cin >> a >> b >> c;
add(a, b, c);
t.a = a, t.b = b, t.c = c;
v.push_back(t);
}
for (int i = 0; i < m; i++)
{
Dijkstra(v[i].b, v[i].a, v[i].c);
}
for (int i = 1; i <= n; i++)
{
if (ans[i] == inf)
cout << -1 << "\n";
else
cout << ans[i] << "\n";
}
return 0;
}