首页 技术 正文
技术 2022年11月13日
0 收藏 360 点赞 5,170 浏览 1719 个字

题目大概说,一辆带有一个容量有限的油箱的车子在一张图上行驶,每行驶一单位长度消耗一单位油,图上的每个点都可以加油,不过都有各自的单位费用,问从起点驾驶到终点的最少花费是多少?

这题自然想到图上DP,通过最短路来转移方程:

  • dp[u][c]表示当前在u点油箱还有c单位油时的最少花费

不过,我T得好惨,因为在转移时我通过枚举在各个结点加多少油转移,这样对于每个状态都for一遍枚举,整个时间复杂度还得乘上转移的代价,即油箱最大容量。。。

事实上,状态dp[u][c]只需要向两个方向转移:

  • 向dp[u][c+1]转移,即原地加一单位油
  • 向dp[v][c-w(u,v)]((u,v)∈E 且 w(u,v)<=c),即走到下一个结点

另外用SPFA会TLE,用Dijkstra即可,1000×100的状态数稳定AC。

 #include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
#define INF (1<<30)
#define MAXN 1111
#define MAXM 111111 struct Edge{
int v,w,next;
}edge[MAXM<<];
int NE,head[MAXN];
void addEdge(int u,int v,int w){
edge[NE].v=v; edge[NE].w=w; edge[NE].next=head[u];
head[u]=NE++;
} int vs,vt,cap;
int price[MAXN],d[MAXN][];
bool vis[MAXN][]; struct Node{
int u,w,d;
Node(int _u=,int _w=,int _d=):u(_u),w(_w),d(_d){}
bool operator<(const Node &nd)const{
return nd.d<d;
}
}; int dijkstra(){
memset(d,,sizeof(d));
memset(vis,,sizeof(vis));
priority_queue<Node> que;
for(int i=; i<=cap; ++i){
d[vs][i]=price[vs]*i;
que.push(Node(vs,i,d[vs][i]));
}
while(!que.empty()){
Node nd=que.top(); que.pop();
if(nd.u==vt) return nd.d;
if(vis[nd.u][nd.w]) continue;
vis[nd.u][nd.w]=;
if(nd.w<cap && d[nd.u][nd.w+]>d[nd.u][nd.w]+price[nd.u]){
d[nd.u][nd.w+]=d[nd.u][nd.w]+price[nd.u];
que.push(Node(nd.u,nd.w+,d[nd.u][nd.w+]));
}
for(int i=head[nd.u]; i!=-; i=edge[i].next){
int v=edge[i].v;
if(edge[i].w>nd.w) continue;
int nw=nd.w-edge[i].w;
if(d[v][nw]>d[nd.u][nd.w]){
d[v][nw]=d[nd.u][nd.w];
que.push(Node(v,nw,d[v][nw]));
}
}
}
return INF;
} int main(){
int n,m,q,a,b,c;
scanf("%d%d",&n,&m);
for(int i=; i<n; ++i){
scanf("%d",price+i);
}
memset(head,-,sizeof(head));
while(m--){
scanf("%d%d%d",&a,&b,&c);
addEdge(a,b,c);
addEdge(b,a,c);
}
scanf("%d",&q);
while(q--){
scanf("%d%d%d",&cap,&vs,&vt);
int res=dijkstra();
if(res==INF) puts("impossible");
else printf("%d\n",res);
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295