PAT (Advanced Level) Practice_1018 Public Bike Management (30 分)_多种最短路径的再处理(记录前驱)

  • 题目地址
  • 题目分析:在dijkstra算法得到最短路径的过程中,利用pre记录最短路径的不同到达方式。再对pre进行DFS即可计算并比较need需要带去的车子和cap途中保留下来的车子(即带回的车子数目)。我这里的递归计算方式的逻辑建立在1、后面多的车子不会补充前面;2、前面多的车子后面可以补充。通过dif计算前一站的差值,再分析得到need和cap,继续递归到终点比较。
  • 我的代码:
    #include
    #include
    #include
    #define INF 0x3f3f3f3f
    using namespace std;
    
    int c, n, s, m, aa[501][501], bb[501], num[501];
    bool flag[501] = { false };
    int anss = INF, ansb = INF;
    vectortemp, ans, pre[501];
    
    void dfs(int node, int need, int cap)
    {
    	if ((node == 0) && ((need < anss) || (need == anss && cap < ansb)))
    	{
    		anss = need, ansb = cap;
    		ans.clear();
    		for (auto it = temp.begin(); it != temp.end(); it++)
    			ans.push_back(*it);
    	}
    	temp.push_back(node);
    	for (int i = 0; i < pre[node].size(); i++)
    	{
    		int dif = need - num[pre[node][i]];
    		dfs(pre[node][i], dif >= 0 ? dif : 0, dif >= 0 ? cap : cap - dif);
    	}
    	temp.erase(temp.end() - 1);
    }
    
    int main()
    {
    	scanf("%d %d %d %d", &c, &n, &s, &m);
    	fill(aa[0], aa[0] + 501 * 501, INF);
    	for (int i = 1; i <= n; i++)
    	{
    		scanf("%d", &num[i]);
    		num[i] = num[i] - c / 2;
    	}
    	for (int i = 0, a, b, l; i < m; i++)
    	{
    		scanf("%d %d %d", &a, &b, &l);
    		aa[a][b] = aa[b][a] = l;
    	}
    
    	fill(bb, bb + 501, INF);
    	bb[0] = 0;
    	while (true)
    	{
    		int val = INF, id;
    		for (int i = 0; i <= n; i++)
    			if (!flag[i] && bb[i] < val)
    				val = bb[i], id = i;
    		if (val == INF || id == s) break;
    		flag[id] = true;
    
    		for (int i = 0; i <= n; i++)
    		{
    			if (!flag[i] && val + aa[id][i] < bb[i])
    			{
    				bb[i] = val + aa[id][i];
    				pre[i].clear();
    				pre[i].push_back(id);
    			}
    			else if (!flag[i] && val + aa[id][i] == bb[i])
    				pre[i].push_back(id);
    		}
    	}
    	dfs(s, num[s] >= 0 ? 0 : -num[s], num[s] >= 0 ? num[s] : 0);
    
    	printf("%d 0", anss);
    	for (int i = ans.size() - 1; i >= 0; i--)
    		printf("->%d", ans[i]);
    	printf(" %d", ansb);
    
    	return 0;
    }

     

你可能感兴趣的:(PAT,(Advanced,Level),Practice)