solution
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
const int INF = 0x3f3f3f;
using namespace std;
const int N = 510;
int map[N][N], dis[N], weight[N], vis[N], minNeed=INF, minBack=INF;
int cmax, n, sp, m;
vector<int> path, temppath, pre[N];
void dfs(int v)
{
temppath.push_back(v);
if (v == 0)
{
int book = 0, need = 0;
for (int i = temppath.size() - 1; i >= 0; i--)
{
int id=temppath[i];
if (weight[id] > 0)
{
book += weight[id];
}
else if (weight[id] + book > 0)
{
book += weight[id];
}
else
{
need += -(weight[id] + book);
book = 0;
}
}
if (need < minNeed)
{
minNeed = need;
minBack = book;
path = temppath;
}
else if (need == minNeed && book < minBack)
{
minBack = book;
path = temppath;
}
temppath.pop_back();
return;
}
for (int i = 0; i < pre[v].size(); i++)
{
dfs(pre[v][i]);
}
temppath.pop_back();
}
int main()
{
cin >> cmax >> n >> sp >> m;
for (int i = 1; i <= n; i++)
{
cin >> weight[i];
weight[i] -= (cmax >> 1);
}
memset(map, INF, sizeof map);
memset(dis, INF, sizeof dis);
for (int i = 1; i <= m; i++)
{
int x, y, z;
cin >> x >> y >> z;
map[x][y] = z, map[y][x] = z;
}
dis[0] = 0;
for (int i = 0; i <= n; i++)
{
int v = -1,tans=INF;
for (int j = 0; j <= n; j++)
{
if (!vis[j] && dis[j] < tans)
{
v = j;
tans = dis[j];
}
}
if (v == -1)
break;
vis[v] = true;
for (int j = 0; j <= n; j++)
{
if (!vis[j] && map[v][j]!=INF)
{
if (dis[j] == dis[v] + map[v][j])
{
pre[j].push_back(v);
}
else if (dis[j] > dis[v] + map[v][j])
{
dis[j] = dis[v] + map[v][j];
pre[j].clear();
pre[j].push_back(v);
}
}
}
}
dfs(sp);
cout << minNeed << " 0";
for (int i = path.size() - 2; i >= 0; i--)
{
cout << "->" << path[i];
}
cout<<" "<<minBack;
}