【题目链接】
【算法】
令cost(i,j) = 第i天到第j天走相同的路线,路线长度的最小值
那么,只需筛选出第i天到第j天可以装卸货物的码头,然后将这些码头之间连边,跑弗洛伊德(或其它最短路算法),即可
然后,我们用f[i]表示前i天,总成本最小是多少,显然有 :
f[i] = max{f[j-1] + cost(j,i) * (i - j + 1) + k}
特别地,f[0] = -k
那么,最后的答案就是f[n]
【代码】
#include<bits/stdc++.h>
using namespace std;
#define MAXN 110
#define MAXM 30
const long long INF = 2e9;
long long n,m,k,e,i,j,u,v,w,d,a,b,pos;
long long g[MAXM][MAXM],mark[MAXM][MAXN],f[MAXN];
inline long long calc(long long l,long long r)
{
long long i,j,k;
static bool flag[MAXM];
static long long dist[MAXM][MAXM];
memset(flag,false,sizeof(flag));
for (i = 1; i <= m; i++)
{
for (j = l; j <= r; j++)
{
flag[i] |= mark[i][j];
}
}
for (i = 1; i <= m; i++)
{
for (j = 1; j <= m; j++)
{
if (i == j) dist[i][j] = 0;
else if ((!flag[i]) && (!flag[j])) dist[i][j] = g[i][j];
else dist[i][j] = INF;
}
}
for (k = 1; k <= m; k++)
{
for (i = 1; i <= m; i++)
{
if (i == k) continue;
for (j = 1; j <= m; j++)
{
if (i == j || k == j) continue;
dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j]);
}
}
}
return dist[1][m];
}
int main() {
scanf("%lld%lld%lld%lld",&n,&m,&k,&e);
for (i = 1; i <= m; i++)
{
for (j = 1; j <= m; j++)
{
if (i != j) g[i][j] = INF;
}
}
for (i = 1; i <= e; i++)
{
scanf("%lld%lld%lld",&u,&v,&w);
g[u][v] = g[v][u] = min(g[u][v],w);
}
scanf("%lld",&d);
for (i = 1; i <= d; i++)
{
scanf("%lld%lld%lld",&pos,&a,&b);
mark[pos][a]++; mark[pos][b+1]--;
}
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
mark[i][j] += mark[i][j-1];
}
}
f[0] = -k;
for (i = 1; i <= n; i++) f[i] = INF;
for (i = 1; i <= n; i++)
{
for (j = i; j >= 1; j--)
{
f[i] = min(f[i],f[j-1] + calc(j,i) * (i - j + 1) + k);
}
}
printf("%lld\n",f[n]);
return 0;
}