From 33ce94181397055de479e7fc708086ec8f2e7782 Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Thu, 5 Jan 2023 21:54:14 +0800 Subject: [PATCH] P4878 [USACO05DEC]Layout G https://www.luogu.com.cn/record/98781737 --- Luogu/P4878/P4878.cpp | 90 +++++++++++++++++++++++++++++++++++ Luogu/P4878/data/P4878_14.in | 3 ++ Luogu/P4878/data/P4878_14.out | 3 ++ 3 files changed, 96 insertions(+) create mode 100644 Luogu/P4878/P4878.cpp create mode 100644 Luogu/P4878/data/P4878_14.in create mode 100644 Luogu/P4878/data/P4878_14.out diff --git a/Luogu/P4878/P4878.cpp b/Luogu/P4878/P4878.cpp new file mode 100644 index 00000000..00f9b568 --- /dev/null +++ b/Luogu/P4878/P4878.cpp @@ -0,0 +1,90 @@ +#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(int s) { + 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(s); + dist[s] = 0; + vis[s] = 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; i <= n; i++) { + g[0].emplace_back(i, 0); + } + + for (int i = 2; i <= n; i++) { + g[i].emplace_back(i - 1, 0); + } + + 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(0) && spfa(1)) { + cout << (dist[n] == INF ? -2 : dist[n]) << endl; + } else { + cout << -1 << endl; + } + + return 0; +} diff --git a/Luogu/P4878/data/P4878_14.in b/Luogu/P4878/data/P4878_14.in new file mode 100644 index 00000000..3b42db78 --- /dev/null +++ b/Luogu/P4878/data/P4878_14.in @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89796c9e4b88da1ef9407457d36dba06183d5b4a31959557228740fad13deda2 +size 23 diff --git a/Luogu/P4878/data/P4878_14.out b/Luogu/P4878/data/P4878_14.out new file mode 100644 index 00000000..38c5185d --- /dev/null +++ b/Luogu/P4878/data/P4878_14.out @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:186a919b8c7cb84aebf4e53c70cd1cc028a93a1d183ee29dd6e10cd18a714577 +size 4