计算时间减少c ++优化

时间:2018-01-16 16:33:41

标签: c++ performance optimization time

这是我的代码,需要在不到3秒的时间内处理100 * 250 000个数据 由于我对编码很陌生,我可以改进或改变什么来使其更快,更优化? 以下是问题的代码主厨页面:https://www.codechef.com/problems/DEFOREST

// codechef_deforestation.cpp : définit le point d'entrée pour l'application console.
//

#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <ctime>

int main()
{
    clock_t startTime = clock();
    //Read input
    freopen("C:\\somepath\\input.in", "r", stdin);
    freopen("C:\\somepath\\output.out", "w", stdout);
    int t;
    std::cin >> t;
    //std::cout << t << std::endl;
    for (int i = 0; i < t; i++)
    {
        double result = -1;
        int n;
        std::cin >> n;
        //std::cout << t << std::endl;
        std::vector <int> x, h;
        x.resize(n);
        h.resize(n);
        //chargement des données
        for (int j = 0; j < n; j++)
        {
            std::cin >> x[j] >> h[j];
            //std::cout << x[j] << h[j] << std::endl;
        }
        //calcul
        for (int j = 0; j < n; j++)
        {
            for (int k = j+1; k < n; k++)
            {
                //std::cout << "k : " << k << std::endl;
                int diff_x = x[k] - x[j];
                int diff_h = h[k] - h[j];
                if (diff_x == diff_h) //si 45 deg
                {
                    double res_int = sqrt(diff_x*diff_x + diff_h* diff_h);
                    for (int l = j + 1; l < k; l++)
                    {
                        //std::cout << "l : " << l << std::endl;
                        if (h[l] > x[l])
                        {
                            res_int = res_int - (h[l] - x[l]);
                        }
                    }
                    if (res_int > result)
                    {
                        result = res_int;
                    }
                }
            }   
        }
        std::cout << std::setprecision(6) << std::fixed << result << std::endl;
        x.clear();
        h.clear();
    }
    clock_t testTime=clock();
    std::cout << testTime - startTime;
    return 0;
}

freopen()函数需要保持

0 个答案:

没有答案