From 4b559955d0d1c04a76dea1caac912192a4b7c76f Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Thu, 5 Jan 2023 21:41:12 +0800 Subject: [PATCH] =?UTF-8?q?1731.=20[USACO=202005=20Dec]=20Layout=20?= =?UTF-8?q?=E6=8E=92=E9=98=9F=E5=B8=83=E5=B1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://hydro.ac/d/bzoj/record/63b6d364291ec3514f4e3b50 --- BZOJ/1731/1731.cpp | 82 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 BZOJ/1731/1731.cpp diff --git a/BZOJ/1731/1731.cpp b/BZOJ/1731/1731.cpp new file mode 100644 index 00000000..0a663e97 --- /dev/null +++ b/BZOJ/1731/1731.cpp @@ -0,0 +1,82 @@ +#include +#include +#include +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 1005; +const int INF = 0x3f3f3f3f; + +int n, ml, md, cnt[N], dist[N]; +std::vector> g[N]; +bool vis[N]; + +bool spfa() { + std::fill(std::begin(cnt), std::end(cnt), 0); + std::fill(std::begin(vis), std::end(vis), false); + std::fill(std::begin(dist), std::end(dist), INF); + + std::queue q; + + q.emplace(1); + dist[1] = 0; + vis[1] = true; + + while (!q.empty()) { + int u = q.front(); + q.pop(); + + vis[u] = false; + + for (auto e : g[u]) { + int v = e.first, + w = e.second; + + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + + if (!vis[v]) { + cnt[v] = cnt[u] + 1; + + if (cnt[v] >= n) return false; + + vis[v] = true; + q.emplace(v); + } + } + } + } + + return true; +} + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n >> ml >> md; + + for (int i = 1, a, b, c; i <= ml; i++) { + cin >> a >> b >> c; + + g[a].emplace_back(b, c); + } + + for (int i = 1, a, b, c; i <= md; i++) { + cin >> a >> b >> c; + + g[b].emplace_back(a, -c); + } + + if (!spfa()) { + cout << -1 << endl; + } else { + cout << (dist[n] == INF ? -2 : dist[n]) << endl; + } + + return 0; +}