容易发现DP的做法,dp[i]表示1-i天的最小代价。令cost[i][j]表示i-j天用同一条路的最小价值。
则有 dp[i]=dp[j]+cost[j+1][i]*(i-j)+k (j<i).
cost[i][j]可以用n^2次最短路求出来。由于最短路用的是堆优化dijkstra。
所以复杂度为O(n^2+m^2*ElogE).
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi acos(-1.0) # define eps 1e-3 # define MOD 1000000007 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; int Scan() { int res=0, flag=0; char ch; if((ch=getchar())=='-') flag=1; else if(ch>='0'&&ch<='9') res=ch-'0'; while((ch=getchar())>='0'&&ch<='9') res=res*10+(ch-'0'); return flag?-res:res; } void Out(int a) { if(a<0) {putchar('-'); a=-a;} if(a>=10) Out(a/10); putchar(a%10+'0'); } const int N=1000; //Code begin... struct Edge{int p, next, w;}edge[N*N*4]; int head[N], cnt=1, cost[105][105], node[N], dis[N]; LL dp[N]; bool vis[N]; vector<PII>tim[N]; struct qnode{ int v, c; qnode(int _v=0, int _c=0):v(_v),c(_c){} bool operator <(const qnode &r)const{return c>r.c;} }; void add_edge(int u, int v, int w) { edge[cnt].p=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++; } void dij(int n, int start) { mem(vis,0); FOR(i,1,n) dis[i]=INF; priority_queue<qnode>que; while (!que.empty()) que.pop(); dis[start]=0; que.push(qnode(start,0)); qnode tmp; while (!que.empty()) { tmp=que.top(); que.pop(); int u=tmp.v; if (vis[u]) continue; vis[u]=true; for (int i=head[u]; i; i=edge[i].next) { int v=edge[i].p; if (!vis[v]&&!node[v]&&dis[v]>dis[u]+edge[i].w) { dis[v]=dis[u]+edge[i].w; que.push(qnode(v,dis[v])); } } } } int main () { int n, m, k, d, e, u, v, w; scanf("%d%d%d%d",&n,&m,&k,&e); while (e--) scanf("%d%d%d",&u,&v,&w), add_edge(u,v,w), add_edge(v,u,w); scanf("%d",&d); FOR(i,1,d) scanf("%d%d%d",&u,&v,&w), tim[u].pb(mp(v,w)); FOR(i,1,n) FOR(j,i,n) { mem(node,0); FOR(k,1,m) FO(l,0,tim[k].size()) { int fi=tim[k][l].first, se=tim[k][l].second; if ((fi>=i&&se<=j)||(i>=fi&&i<=se)||(j>=fi&&j<=se)) {node[k]=1; break;} } dij(m,1); cost[i][j]=dis[m]; } dp[1]=cost[1][1]; FOR(i,2,n) { dp[i]=(LL)cost[1][i]*i; FO(j,1,i) dp[i]=min(dp[i],dp[j]+(LL)cost[j+1][i]*(i-j)+k); } printf("%lld ",dp[n]); return 0; }