1 條題解

  • 0
    @ 2025-7-7 16:23:49

    题目大意

    有 NN 个节点 MM 条边的无向图,点权 pip_i 为油价,边权 did_i 为油耗。对于多次询问,寻找一条从 ss 到 ee 的路径,使得汽车油箱内的油量始终满足 0≤fuel≤c0 \le fuel \le c,且购买汽油的花费 costcost 最小。

    解题思路

    用三元组 (city,fuel,cost)(city,fuel,cost) 表示:到达 citycity 时,油箱内有 fuelfuel 升油,花掉了 costcost 元钱。此时有两种选择:

    1. 若 fuel<cfuel<c,可以买 11 升油。转移到 (city,fuel+1,cost+pcity)(city,fuel+1,cost+p_{city})。
    2. 若 d(city,town)≤fueld_{(city,town)} \le fuel,可以前往 towntown。转移到 (city,fuel−d(city,town),cost)(city,fuel-d_{(city,town)},cost)。

    汽车出发时的状态是 (s,0,0)(s,0,0)。每次把新状态加入优先队列,依照 costcost 升序排序。取出队头进行扩展,当首次 city=ecity=e 时有最优解。

    参考代码

    存图为邻接表。

    #include<bits/stdc++.h>
    using namespace std;
    #define ull unsigned long long
    #define ll long long
    #define ld long double
    
    const int maxn=1000+10,maxc=100+10;
    
    int n,m,u,v,d,c,s,e,q;
    int p[maxn];
    vector<int>head[maxn],val[maxn];
    bool vis[maxn][maxc];
    
    void add_edge(int u,int v,int value)
    {
    	head[u].push_back(v);
    	val[u].push_back(value);
    	return;
    }
    
    struct state
    {
    	int city,fuel,cost;
    	bool operator < (const state &x) const {return cost>x.cost;};
    };
    
    void bfs()
    {
    	priority_queue<state>q;
    	memset(vis,false,sizeof(vis));
    	q.push((state){s,0,0});
    	
    	while (q.size())
    	{
    		int u=q.top().city,v=q.top().fuel,w=q.top().cost;
    		q.pop();
    		vis[u][v]=true;
    		if (u==e)
    		{
    			cout<<w<<"\n";
    			return;
    		}
    		if (v<c&&!vis[u][v+1]) q.push((state){u,v+1,w+p[u]});
    		for (int i=0;i<head[u].size();i++)
    		{
    			if (v>=val[u][i]&&!vis[head[u][i]][v-val[u][i]])
    			{
    				q.push((state){head[u][i],v-val[u][i],w});
    			}
    		}
    	}
    	
    	cout<<"impossible\n";
    	return; 
    }
    
    int main()
    {
    	cin>>n>>m;
    	for (int i=0;i<n;i++) cin>>p[i];
    	for (int i=0;i<m;i++)
    	{
    		cin>>u>>v>>d;
    		add_edge(u,v,d);
    		add_edge(v,u,d);
    	}
    	cin>>q;
    	for (int i=0;i<q;i++)
    	{
    		cin>>c>>s>>e;
    		bfs();
    	}
    	
    	return 0;
    }
    
    • 1

    資訊

    ID
    31
    時間
    1000ms
    記憶體
    256MiB
    難度
    3
    標籤
    遞交數
    5
    已透過
    3
    上傳者