📌  相关文章
📜  给定 N 个范围内所有整数的总和

📅  最后修改于: 2022-05-13 01:56:05.371000             🧑  作者: Mango

给定 N 个范围内所有整数的总和

给定N[L, R]形式的范围,任务是找到位于任何给定范围内的所有整数的总和。

例子

方法:给定的问题可以通过类似于合并重叠区间问题的方法来解决。以下是要遵循的步骤:

  • 根据L的升序对区间进行排序。
  • 将第一个间隔压入堆栈,并为每个间隔执行以下操作:
    • 如果当前间隔不与栈顶重叠,则推送它。
    • 如果当前区间与栈顶重叠,且当前区间右端大于栈顶,则用当前区间右端的值更新栈顶。
  • 遍历所有区间后,剩余的堆栈包含合并的区间。合并区间的总和可以使用算术级数之和的公式计算,因为范围[L, R]形成一个 AP,其公差为1 ,元素数为R – L + 1 。总和为((L + R)*(R-L+1))/2。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
#define ll long long
using namespace std;
 
// Function to find the sum of all
// integers numbers in range [L, R]
ll sumInRange(long L, long R)
{
    ll Sum = ((R - L + 1) / 2)
      * (2 * L + (R - L));
    return Sum;
}
 
// Function to find sum of all integers
// that lie in any of the given ranges
ll calcSum(vector > data,
           int n)
{
 
    // Sort intervals in increasing order
    // according to their first element
    sort(data.begin(), data.end());
 
    // Merging the overlaping intervals
    int i, idx = 0;
 
    // Loop to iterate through the array
    for (i = 1; i < n; i++) {
 
        // If current interval overlaps
        // with the previous intervals
        if ((data[idx].second >=
             data[i].first)
            || (data[i].first ==
                data[idx].second + 1)) {
 
            // Merge the previou and the
            // current interval
            data[idx].second
                = max(data[idx].second,
                      data[i].second);
        }
        else {
            idx++;
            data[idx].second = data[i].second;
            data[idx].first = data[i].first;
        }
    }
 
    // Stores the required sum
    ll Sum = 0;
 
    // Loop to calculate the sum of all
    // the remaining merged intervals
    for (i = 0; i <= idx; i++) {
 
        // Add sum of integers
        // in current range
        Sum += sumInRange(data[i].first,
                          data[i].second);
    }
 
    // Return the total Sum
    return Sum;
}
 
// Driver Code
int main()
{
    vector > vec
      = { { -12, 15 },
         { 3, 9 },
         { -5, -2 },
         { 20, 25 },
         { 16, 20 } };
 
    cout << calcSum(vec, vec.size());
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to find the sum of all
// integers numbers in range [L, R]
static int sumInRange(int L, int R)
{
    int Sum = ((R - L + 1) / 2)
      * (2 * L + (R - L));
    return Sum;
}
 
// Function to find sum of all integers
// that lie in any of the given ranges
static int calcSum(int [][]data,
           int n)
{
 
    // Sort intervals in increasing order
    // according to their first element
    Arrays.sort(data,(a,b)->{
        return a[0]-b[0];
    });
 
    // Merging the overlaping intervals
    int i, idx = 0;
 
    // Loop to iterate through the array
    for (i = 1; i < n; i++) {
 
        // If current interval overlaps
        // with the previous intervals
        if ((data[idx][1] >=
             data[i][0])
            || (data[i][0] ==
                data[idx][1] + 1)) {
 
            // Merge the previou and the
            // current interval
            data[idx][1]
                = Math.max(data[idx][1],
                      data[i][1]);
        }
        else {
            idx++;
            data[idx][1] = data[i][1];
            data[idx][0] = data[i][0];
        }
    }
 
    // Stores the required sum
    int Sum = 0;
 
    // Loop to calculate the sum of all
    // the remaining merged intervals
    for (i = 0; i <= idx; i++) {
 
        // Add sum of integers
        // in current range
        Sum += sumInRange(data[i][0],
                          data[i][1]);
    }
 
    // Return the total Sum
    return Sum;
}
 
// Driver Code
public static void main(String[] args)
{
    int [][]vec
      = { { -12, 15 },
         { 3, 9 },
         { -5, -2 },
         { 20, 25 },
         { 16, 20 } };
 
    System.out.print(calcSum(vec, vec.length));
 
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python 3 program for the above approach
 
# Function to find the sum of all
# integers numbers in range [L, R]
def sumInRange(L, R):
 
    Sum = ((R - L + 1) // 2) * (2 * L + (R - L))
    return Sum
 
# Function to find sum of all integers
# that lie in any of the given ranges
def calcSum(data,
            n):
 
    # Sort intervals in increasing order
    # according to their first element
    data.sort()
 
    # Merging the overlaping intervals
    idx = 0
 
    # Loop to iterate through the array
    for i in range(1, n):
 
        # If current interval overlaps
        # with the previous intervals
        if ((data[idx][1] >=
             data[i][0])
            or (data[i][0] ==
                data[idx][1] + 1)):
 
            # Merge the previou and the
            # current interval
            data[idx][1] = max(data[idx][1],
                               data[i][1])
 
        else:
            idx += 1
            data[idx][1] = data[i][1]
            data[idx][0] = data[i][0]
    # Stores the required sum
    Sum = 0
 
    # Loop to calculate the sum of all
    # the remaining merged intervals
    for i in range(idx+1):
 
        # Add sum of integers
        # in current range
        Sum += sumInRange(data[i][0],
                          data[i][1])
 
    # Return the total Sum
    return Sum
 
# Driver Code
if __name__ == "__main__":
 
    vec = [[-12, 15],
           [3, 9],
           [-5, -2],
           [20, 25],
           [16, 20]]
 
    print(calcSum(vec, len(vec)))
 
    # This code is contributed by ukasp.


Javascript



输出
247

时间复杂度: O(N*log N)
辅助空间: O(1)