POJ 3169 Layout
传送门
同 AcWing 1170 排队布局、洛谷 P4878 [USACO05DEC]Layout G
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
typedef pair<int, int> p;
const int inf(0x3f3f3f3f);
const int maxn(1e3 + 10);
const int maxm(5e4 + 10);
bool vis[maxn];
int ecnt, head[maxn], dis[maxn], cnt[maxn];
struct edge {
int to, wt, nxt;
} edges[maxm];
template<typename T>
inline const T read()
{
T x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 3) + (x << 1) + ch - '0';
ch = getchar();
}
return x * f;
}
template<typename T>
inline void write(T x, bool ln)
{
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) write(x / 10, false);
putchar(x % 10 + '0');
if (ln) putchar(10);
}
void addEdge(int u, int v, int w)
{
edges[ecnt].to = v;
edges[ecnt].wt = w;
edges[ecnt].nxt = head[u];
head[u] = ecnt++;
}
bool spfa(int n, int src)
{
memset(dis, 0x3f, sizeof dis);
memset(vis, false, sizeof vis);
memset(cnt, 0, sizeof cnt);
dis[src] = 0;
vis[src] = true;
queue<int> q;
q.push(src);
while (not q.empty()) {
int u = q.front();
q.pop();
vis[u] = false;
for (int i = head[u]; compl i; i = edges[i].nxt) {
int v = edges[i].to, w = edges[i].wt;
if (dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
if (not vis[v]) {
vis[v] = true;
q.push(v);
cnt[v] = cnt[u] + 1;
if (cnt[v] >= n + 1) {
return false;
}
}
}
}
}
return true;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("input.txt", "r", stdin);
#endif
ios::sync_with_stdio(false);
memset(head, -1, sizeof head);
int n = read<int>(), ml = read<int>(), md = read<int>();
for (int i = 1; i < n; ++i) {
addEdge(i + 1, i, 0);
}
for (int i = 1; i <= n; ++i) {
addEdge(0, i, 0);
}
while (ml--) {
int u = read<int>(), v = read<int>(), w = read<int>();
if (v < u) swap(u, v);
addEdge(u, v, w);
}
while (md--) {
int u = read<int>(), v = read<int>(), w = read<int>();
if (v < u) swap(u, v);
addEdge(v, u, -w);
}
if (not spfa(n, 0)) {
printf("-1\n");
} else {
spfa(n, 1);
printf("%d\n", dis[n] == inf ? -2 : dis[n]);
}
return 0;
}