首页 > 解决方案 > 如何减少此 C++ 代码的运行时间?

问题描述

任务是减少以下程序的运行时间。我们有一个包含 n 个元素的数组 A,我们以两个整数的形式输入 q 个查询,两个整数都用空格分隔。我们需要找到对 (x,y) 的数量,使得 x<y 并且数组的第 x和第 y个元素的乘积是偶数。

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


int main() {
    int n,q; //n is the size of array arr and q is the number of queries asked
    cin>>n>>q;
    int arr[n];
    int b,a,count=0;
    //Initialization of array elements
    for(int i=0;i<n;i++){
        scanf("%d",&arr[i]);
    }
    //Taking q queries with two integers such that a<=x<=b and a<=y<=b. We need to find pairs (x,y) such that x<y and (arr[x-1]*arr[y-1]) is even.
    for(int i=0;i<q;i++){
        cin>>a>>b;
        for(int x=a;x<=b;x++){
            for (int y=a;y<=b;y++){
                if ((x<y)&&((arr[x-1]*arr[y-1])%2==0)) count++;  //(x,y) is the required pair
            }
        }
        cout<<count<<endl;
        count=0;
    }  
    return 0;
}

标签: c++performanceruntimecoding-efficiency

解决方案


推荐阅读