1 条题解

  • 0
    @ 2025-3-9 20:51:31

    made in China

    #include <iostream>
    #include <vector>
    #include <map>
    #include <algorithm>
    
    using namespace std;
    
    int main() {
        int n;
        cin >> n;
        
        vector<pair<int, long long>> cows(n); // (种族, 坐标)
        
        for (int i = 0; i < n; ++i) {
            cin >> cows[i].first >> cows[i].second;
        }
        
        // Step 1: Sort cows based on their coordinates
        sort(cows.begin(), cows.end(), [](const pair<int, long long>& a, const pair<int, long long>& b) {
            return a.second < b.second;
        });
        
        // Step 2: Initialize balance map and other variables
        map<int, int> balance_map; // balance -> first occurrence index
        balance_map[0] = -1; // balance 0 at index -1 (before the start)
        
        int balance = 0;
        long long max_length = 0;
        
        // Step 3: Traverse sorted cows
        for (int i = 0; i < n; ++i) {
            if (cows[i].first == 0) { // Breed 0
                balance--;
            } else { // Breed 1
                balance++;
            }
            
            // Check if this balance has been seen before
            if (balance_map.find(balance) != balance_map.end()) {
                // Calculate the length of the balanced interval
                int start_index = balance_map[balance];
                long long interval_length = cows[i].second - cows[start_index + 1].second; // Get the coordinates
                max_length = max(max_length, interval_length);
            } else {
                // If not seen, record the first index of this balance
                balance_map[balance] = i;
            }
        }
        
        // Output the result
        cout << max_length << endl;
        return 0;
    }
    

    信息

    ID
    2476
    时间
    1000ms
    内存
    256MiB
    难度
    9
    标签
    递交数
    13
    已通过
    2
    上传者