ABC404 G
Dtw_
·
·
题解
题意
给你 n 个未知数 A_1,A_2,\cdots,A_n 满足 :
求 $\sum A_i$ 的最小值。
## Solution
我们记 $c_i$ 为前缀和数组,那么这题分为 $3$ 步:
* $\displaystyle \sum_{j=L_i}^{R_i} A_j = S_i \to c_{R_i} - c_{L_i - 1} = S_i$
* $c_r - c_{l-1} = S_i \to c_r - c_{l-1} \leq S \ \& \ c_r - c_{l-1}\ge S$
* 由于每个数都得是正整数,所以 $c_i - c_{i-1} \ge 0$。
然后差分约束做完了。答案就是 $c_n$。
## Code
```cpp
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
const int N = 1e5 + 10, inf = 0x3f3f3f3f;
int n, m, c[N];
ll d[N];
bool vis[N];
vector<pair<int, int>> e[N];
bool spfa(int s)
{
queue<int> q; q.push(s);
memset(d, inf, sizeof d);
d[s] = 0; vis[s] = 1;
while (!q.empty()) {
int u = q.front(); q.pop();
vis[u] = 0;
for (auto t : e[u]) {
int v = t.first, w = t.second;
if (d[v] > d[u] + w) {
d[v] = d[u] + w;
c[v] = c[u] + 1;
if (c[v] > n) return false;
if (!vis[v]) q.push(v), vis[v] = 1;
}
}
}
return true;
}
int main()
{
fst
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v, w; cin >> u >> v >> w; u--;
e[u].emplace_back(v, -w);
e[v].emplace_back(u, w);
}
for (int i = 1; i <= n; i++) {
e[i - 1].emplace_back(i, -1);
}
for (int i = 1; i <= n; i++) e[0].emplace_back(i, 0);
if (spfa(0)) cout << -d[n];
else cout << -1;
return 0;
}
```