个人觉得直接放入代码是最管用的。
其他方法类似,题意请参考其他博主。
#include
using namespace std;
const int N = 1e4 + 50;
int maxn = 2000000000;
int c, n, ed, s[N], m, minlen, needn, backn, pre[N];
bool flag, book[N];
vector<pair<int, int > > e[N];
inline void dfs(int u, int points, int maxneed, int stores, int len)
{
if (len > minlen) return ;
int nd = points * c / 2 - stores;
maxneed = max(maxneed, max(0, nd));
if (u == ed) {
int tneedn, tbackn;
if (nd <= 0) {
// dont need
tneedn = maxneed; tbackn = -nd + maxneed;
} else {
// need;
tneedn = max(maxneed, nd); tbackn = 0;
}
if (len == minlen) {
if (needn > tneedn || (needn == tneedn && backn > tbackn)) {
needn = tneedn; backn = tbackn;
}
} else if (minlen > len) {
minlen = len; needn = tneedn; backn = tbackn;
}
return ;
}
for (int i = 0; i < e[u].size(); i++) {
int v = e[u][i].first, w = e[u][i].second;
if (book[v]) continue;
book[v] = true;
dfs(v, points + 1, maxneed, stores + s[v], len + w);
book[v] = false;
}
}
inline void dfs2(int u, int points, int maxneed, int stores, int len)
{
if (flag) return ;
if (len > minlen) return ;
int nd = points * c / 2 - stores;
maxneed = max(maxneed, max(0, nd));
if (u == ed) {
int tneedn, tbackn;
if (nd <= 0) {
// dont need
tneedn = maxneed; tbackn = -nd + maxneed;
} else {
// need;
tneedn = max(maxneed, nd); tbackn = 0;
}
if (len == minlen) {
if (tneedn == needn && tbackn == backn) {
// puts("test 1");
flag = true;
}
}
return ;
}
for (int i = 0; i < e[u].size(); i++) {
int v = e[u][i].first, w = e[u][i].second;
if (book[v]) continue;
book[v] = true;
pre[v] = u;
dfs2(v, points + 1, maxneed, stores + s[v], len + w);
if (flag) return ;
book[v] = false;
}
}
signed main()
{
scanf("%d%d%d%d", &c, &n, &ed, &m);
for (int i = 1; i <= n; i++) scanf("%d", &s[i]);
while (m--) {
int u, v, w; scanf("%d%d%d", &u, &v, &w);
e[u].push_back({v, w});
e[v].push_back({u, w});
}
minlen = maxn, needn = maxn, backn = maxn;
book[0] = true;
dfs(0, 0, 0, 0, 0);
// printf("%d %d %d\n", minlen, needn, backn);
memset(book, 0, sizeof book);
book[0] = true;
dfs2(0, 0, 0, 0, 0);
vector<int > res;
while (ed != 0) {
res.push_back(ed); ed = pre[ed];
}
printf("%d %d", needn, 0);
for (int i = res.size() - 1; i >= 0; i--) {
printf("->%d", res[i]);
}
printf(" %d\n", backn);
return 0;
}