1046 Shortest Distance (20分)

高速公路出口距离计算
本文介绍了一个简单的算法,用于计算高速公路形成简单环形时任意两个出口之间的最短距离。输入包括出口数量、各出口间的距离及若干对出口编号,输出为每对出口间的最短距离。

The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.

Input Specification:

Each input file contains one test case. For each case, the first line contains an integer N (in [3,10​5​​]), followed by N integer distances D​1​​ D​2​​ ⋯ D​N​​, where D​i​​ is the distance between the i-th and the (i+1)-st exits, and D​N​​ is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (≤10​4​​), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 10​7​​.

Output Specification:

For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.

Sample Input:

5 1 2 4 14 9
3
1 3
2 5
4 1

Sample Output:

3
10
7
#include<iostream>
#include<vector>

using namespace std;

int main(){
    int n;
    cin >> n;
    vector<int> vec(n + 1);
    int sum = 0;
    for(int i = 1; i <= n; i++){
        scanf("%d", &vec[i]);
        sum += vec[i];
    }
    int m;
    cin >> m;
    for(int i = 0; i < m; i++){
        int a, b;
        scanf("%d %d", &a, &b);
        int temp = 0;
        if(a > b){

            for(int j = b; j < a; j++){
                temp += vec[j];
            }   

        }else
        {
            for(int j = a; j < b; j++){
                temp += vec[j];
            } 
            
        }
        
        
        if(temp > sum - temp){
            printf("%d\n", sum - temp);        
        }else
        {
            printf("%d\n", temp);  
        }
        

    }

    return 0;
}

 

### 尾递归优化旅行商问题 (TSP) 尾递归是一种通过将递归调用的结果直接返回给上一层调用的方式,避免了额外的栈帧开销。在解决 TSP 问题时,暴力递归方法通常会列出所有可能的路径并计算其总长度,但这种方法可能导致栈溢出或性能瓶颈。为了优化代码,可以采用尾递归形式,并结合辅助函数保存中间状态。 以下是将暴力递归改写为尾递归的具体实现[^1]: ```python def tsp_tail_recursive(distance_matrix, visited=None, current_path=None, current_cost=0, start=0): # 初始化访问状态和路径 if visited is None: visited = [False] * len(distance_matrix) if current_path is None: current_path = [] n = len(distance_matrix) visited[start] = True current_path.append(start) # 如果所有城市都被访问过,计算回路成本并返回 if len(current_path) == n: return current_cost + distance_matrix[start][0], current_path + [0] # 辅助函数用于尾递归调用 def helper(min_cost=float('inf'), best_path=None): for next_city in range(n): if not visited[next_city]: new_cost = current_cost + distance_matrix[start][next_city] cost, path = tsp_tail_recursive( distance_matrix, visited[:], # 深拷贝访问状态 current_path[:], # 深拷贝当前路径 new_cost, next_city ) if cost < min_cost: min_cost = cost best_path = path return min_cost, best_path return helper() ``` #### 代码说明 - **`distance_matrix`**: 表示城市间距离的二维矩阵。 - **`visited`**: 记录哪些城市已经被访问。 - **`current_path`**: 当前路径上的城市序列。 - **`current_cost`**: 当前路径的累计成本。 - **`start`**: 当前所在的城市索引。 上述代码中,通过 `helper` 函数实现了尾递归调用,避免了每次递归调用后需要额外的栈空间来存储中间结果。每次递归仅依赖当前状态和累积结果,从而显著提高了性能。 #### 注意事项 尽管 Python 解释器不支持自动优化尾递归,但上述代码通过手动管理状态变量模拟了尾递归的效果。对于非常大的输入规模,仍可能遇到栈溢出问题,此时建议使用迭代方法或其他更高效的算法(如动态规划或启发式搜索)。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值