马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
传送门:https://pintia.cn/problem-sets/994805342720868352/problems/994805489282433024
解:
迪杰斯特拉+DFS(模板)#include <cstdio>
#include <climits>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 510;
int c_max, n, sp, m;
int pw[maxn];
int d[maxn];
bool vis[maxn];
int G[maxn][maxn];
vector<int> pre[maxn];
void DJS(void)
{
fill(d, d + maxn, INT_MAX);
memset(vis, false, sizeof(vis));
d[0] = 0;
for (int i = 0; i < n; i++)
{
int u = -1, min = INT_MAX;
for (int j = 0; j <= n; j++)
if (!vis[j] && d[j] < min) min = d[u = j];
if (u == -1) return;
vis[u] = true;
for (int v = 1; v <= n; v++)
{
if (vis[v] || G[u][v] == INT_MAX) continue;
if (G[u][v] + d[u] < d[v])
{
d[v] = G[u][v] + d[u];
pre[v].clear();
pre[v].push_back(u);
}
else if (G[u][v] + d[u] == d[v])
pre[v].push_back(u);
}
}
}
vector<int> path, temp_path;
int send = INT_MAX, back = INT_MAX;
void DFS(int id)
{
if (!id)
{
int sen = 0, bac = 0;
for (int i = temp_path.size() - 1; i >= 0; i--)
{
bac += pw[temp_path[i]];
if (bac < 0)
{
sen -= bac;
bac = 0;
}
}
if (sen < send || (sen == send && bac < back))
{
path = temp_path;
send = sen;
back = bac;
}
}
temp_path.push_back(id);
for (int i = 0; i < pre[id].size(); i++)
DFS(pre[id][i]);
temp_path.pop_back();
}
int main(void)
{
// freopen("input.txt", "r", stdin);
scanf("%d %d %d %d", &c_max, &n, &sp, &m);
for (int i = 1; i <= n; i++)
{
scanf("%d", pw + i);
pw[i] -= c_max / 2;
}
fill(G[0], G[0] + maxn * maxn, INT_MAX);
while (m--)
{
int a, b, l;
scanf("%d %d %d", &a, &b, &l);
G[a][b] = G[b][a] = l;
}
DJS();
DFS(sp);
printf("%d 0", send);
for (int i = path.size() - 1; i >= 0; i--)
printf("->%d", path[i]);
printf(" %d", back);
return 0;
}
|