R257983 2025-03-19 23:39 采纳率: 25%
浏览 3

《解决旅行者过桥问题的经典算法分析与实现》

img


#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return *(int *)a - *(int *)b;
}

int main() {
    int n;
    while (scanf("%d", &n) != EOF) {
        int a[1005];
        for (int i = 0; i < n; i++) {
            scanf("%d", &a[i]);
        }

        // 对数组进行排序

        qsort(a, n, sizeof(int), compare);
        
        long long total = 0;
        int left = 0, right = n - 1;
        
        // 使用双指针方法进行计算
        while (right - left > 2) {
            long long s1 = 2LL * a[left] + a[right] + a[right - 1];
            long long s2 = a[left] + 2LL * a[left + 1] + a[right];
            total += (s1 < s2) ? s1 : s2;
            right -= 2;
        }
        
        // 处理剩下的3个或更少的元素
        if (right - left == 2) {
            total += a[left] + a[left + 1] + a[left + 2];
        } else if (right - left == 1) {
            total += a[left + 1];
        } else if (right - left == 0) {
            total += a[left];
        }

        // 输出结果
        printf("%lld\n", total); // 使用%lld适应Linux环境
    }
    return 0;
}

#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return *(int *)a - *(int *)b;
}

int main() {
    int n;
    while (scanf("%d", &n) != EOF) {
        int a[1005];
        for (int i = 0; i < n; i++) {
            scanf("%d", &a[i]);
        }
        qsort(a, n, sizeof(int), compare);
        long long total = 0;
        int m = n;
        while (m > 3) {
            long long s1 = 2LL * a[0] + a[m-1] + a[m-2];
            long long s2 = a[0] + 2LL * a[1] + a[m-1];
            total += (s1 < s2) ? s1 : s2;
            m -= 2;
        }
        if (m == 3) {
            total += a[0] + a[1] + a[2];
        } else if (m == 2) {
            total += a[1];
        } else if (m == 1) {
            total += a[0];
        }
        printf("%lld\n", total);
    }
    return 0;

} 

为何在浙理工的oj系统里过不了,如何解决

  • 写回答

4条回答 默认 最新

  • 道友老李 JWE233286一种基于机器视觉的水表指针读数识别及修正的方法 专利发明者 2025-03-19 23:39
    关注
    让【道友老李】来帮你解答,本回答参考gpt编写,并整理提供,如果还有疑问可以点击头像关注私信或评论。
    如果答案让您满意,请采纳、关注,非常感谢!
    在浙理工的oj系统里过不了可能是因为输入输出格式不符合oj系统的要求,或者是代码中存在逻辑错误导致程序无法正确输出结果。要解决这个问题,可以尝试以下几种方法:
    1. 检查输入输出格式:确保输入输出格式符合oj系统的要求,比如输入结束标记是否正确,输出格式是否完整。
    2. 检查逻辑错误:仔细检查代码中的逻辑错误,确保程序能够正确计算结果。
    3. 测试样例:使用自己准备的测试样例对代码进行调试,找出问题出现的具体位置。
    4. 查看错误信息:在oj系统中查看错误信息,根据错误信息调整代码逻辑。 如果以上方法都无法解决问题,建议参考oj系统的使用说明或者求助相关论坛或教师寻求帮助。
    评论

报告相同问题?

问题事件

  • 创建了问题 3月19日