You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++代码执行超时优化求助:环形数组邻和约束判定问题

Optimizing C++ Code for Circular Permutation Problem (Fixing Timeouts)

Let's fix your code and solve the timeout issue for this circular permutation problem. Here's a step-by-step breakdown of what's wrong with your original code and how to optimize it:

Issues with the Original Code

  • O(n²) Time Complexity: Your SearchInt function sorts the vector every time it's called, which takes O(k log k) time for a vector of size k. Combined with the erase operation (O(k) per call), looping through n elements leads to an overall time complexity of O(n² log n)—way too slow for n=5e5.
  • Redundant Computations: You call SearchInt twice to find the same element's position, wasting unnecessary cycles.
  • No Input/Output Optimization: For large datasets, using standard cin/cout without optimizations will cause significant slowdowns.
  • Integer Overflow Risk: When comparing sums of elements up to 1e9, using int can lead to overflow since 1e9 + 1e9 exceeds the 32-bit int limit.

Correct Approach & Optimized Solution

This problem has a classic efficient solution based on sorting and a simple feasibility check. Here's the core logic:

Key Observations

  1. Feasibility Check: For a valid circular permutation, the largest element must be strictly less than the sum of the second and third largest elements. This is because:
    • All smaller elements will automatically satisfy the condition (their adjacent elements will include at least one larger number, making their sum greater than the element itself).
    • For n=3, this reduces to the triangle inequality (largest < sum of the other two).
  2. Permutation Construction: Once the feasibility condition is met, we can construct a valid permutation in O(n) time by placing the largest element right before the second-largest element in the sorted array. This ensures the largest element is surrounded by two numbers whose sum exceeds it, and all other elements are in an order that satisfies the condition.

Optimized Code

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    // Speed up input/output for large datasets
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;
    // Use long long to avoid overflow when summing large elements
    vector<long long> nums(n);
    for (int i = 0; i < n; ++i) {
        cin >> nums[i];
    }

    sort(nums.begin(), nums.end());

    bool is_possible = false;
    if (n == 3) {
        is_possible = (nums[2] < nums[0] + nums[1]);
    } else {
        is_possible = (nums.back() < nums[n-2] + nums[n-3]);
    }

    if (!is_possible) {
        cout << "NO\n";
        return 0;
    }

    cout << "YES\n";
    if (n == 3) {
        for (long long num : nums) {
            cout << num << " ";
        }
    } else {
        // Output first n-2 elements, then the largest, then the second-largest
        for (int i = 0; i < n-2; ++i) {
            cout << nums[i] << " ";
        }
        cout << nums.back() << " " << nums[n-2];
    }
    cout << "\n";

    return 0;
}

Explanation of Optimizations

  • O(n log n) Time Complexity: The only expensive operation is sorting, which is O(n log n)—perfectly acceptable for n=5e5.
  • Fast Input/Output: ios::sync_with_stdio(false); cin.tie(nullptr); disables synchronization with C I/O and unties cin from cout, drastically speeding up input for large datasets.
  • Overflow Protection: Using long long ensures that sums of elements up to 1e9 don't overflow.
  • Efficient Permutation: Constructing the permutation in a single pass avoids any costly erase or search operations.

Example Verifications

Let's test some cases:

  • Valid Case: n=4, nums=[1,2,3,4]. Sorted: [1,2,3,4]. Feasibility check: 4 < 3+2 → true. Output: 1 2 4 3. All elements satisfy the circular condition.
  • Invalid Case: n=4, nums=[2,2,2,5]. Sorted: [2,2,2,5]. Feasibility check:5 <2+2 → false. Output: NO.
  • n=3 Valid Case: nums=[2,3,4]. Feasibility check:4 <2+3 → true. Output: 2 3 4.

内容的提问来源于stack exchange,提问作者undefined

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 00:13:10