如何减少此C ++代码的运行时间?

时间:2019-11-12 07:17:46

标签: c++ performance runtime coding-efficiency

任务是减少以下程序的运行时间。我们有一个由n个元素组成的数组A,我们以两个整数(均用一个空格隔开)的形式接受q个查询。我们需要找到对(x,y)的数量,以使x th 和y th 元素的乘积是偶数。

#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;
}

0 个答案:

没有答案