打印包含范围[0,m]值的大小 n 的数组

原文:

给定大小为 n 的数组arr【】,该数组包含具有从 0 到(m–1)的状态的循环变量(即,当从 m-1 递增时,它转到 0 )。任务是完成以下两种类型的 q 查询:

  • 第一种类型:1l r k–循环递增指数[l,r]范围内的所有值,k 次。
  • 第二种类型:2l r–打印索引范围内的更新值[l,r]。

示例:

输入: arr[] = {2,2,7,2,5},q = 5,m = 8 查询[][] = {{1,0,3,4}, {1,4,4,2}, {1,0,0,7}, {2,1,3}, {2,3,3}} 输出: {6,3,6},{6} 3,6,7} 所以在索引 1 到 3 的第 4 个查询元素和索引 3 的第 5 个查询元素中都会打印。

输入: arr[] = [2,3,4,5],q = 3,m = 6 查询[][] = {{1,0,0,3}, {1,1,2,2}, {1,3,3,1}, {2,0,3}} 输出: {5,5,1,1}

方法:问题可以用贪心法解决。按照以下步骤实施该方法:

  • 当查询是第一种类型时,更新范围[l,r]内的所有值,k 次。
  • 当查询是第二种类型时,打印范围[1,r]内的值。

下面是上述方法的实现。

c 14

// c   code to implement above approach
#include 
using namespace std;
// function to implement the queries
void update(int arr[], int n, int m, int q,
            vector >& queries)
{
    // loop to implement the queries
    for (int i = 0; i < q; i  ) {
        if (queries[i][0] == 1) {
            for (int j = queries[i][1];
                 j <= queries[i][2];
                 j  )
                arr[j] = (arr[j]  
                          queries[i][3]) % m;
        }
        else if (queries[i][0] == 2) {
            for (int j = queries[i][1];
                 j <= queries[i][2];
                 j  )
                cout << arr[j] << " ";
            cout << endl;
        }
    }
}
// driver's code
int main()
{
    int n = 5, m = 8, q = 5;
    int arr[] = { 2, 2, 7, 2, 5 };
    vector > queries(q);
    queries[0] = { 1, 0, 3, 4 };
    queries[1] = { 1, 4, 4, 2 };
    queries[2] = { 1, 0, 0, 7 };
    queries[3] = { 2, 1, 3 };
    queries[4] = { 2, 3, 3 };
    update(arr, n, m, q, queries);
    return 0;
}

python 3

# python3 code to implement above approach
# function to implement the queries
def update(arr, n, m,  q, queries):
    # loop to implement the queries
    for i in range(q):
        if (queries[i][0] == 1):
            for j in range(queries[i][1],
                           queries[i][2]   1):
                arr[j] = (arr[j]  
                          queries[i][3]) % m
        elif (queries[i][0] == 2):
            for j in range(queries[i][1],
                           queries[i][2]   1):
                print(arr[j], end = " ")
            print()
# driver code
if __name__ == "__main__":
    n = 5
    m = 8
    q = 5
    arr = [2, 2, 7, 2, 5]
    queries = []
    queries.append([1, 0, 3, 4])
    queries.append([1, 4, 4, 2])
    queries.append([1, 0, 0, 7])
    queries.append([2, 1, 3])
    queries.append([2, 3, 3])
    update(arr, n, m, q, queries)
# this code is contributed by ukasp

java 描述语言


output

6 3 6 
6 

时间复杂度: o(qn) 辅助空间:* o(1)