2

I tried to solve the Area problem http://www.infoarena.ro/problema/aria, but with the first code i receive Time Limit Exceeded while with the second everything works fine. So, what is the difference between these two?

#include <fstream>
#include <vector>
#include <stdlib.h>
#include <iomanip>
#include <cmath>
#define max 1000000
using namespace std;

ifstream fin("aria.in");
ofstream fout("aria.out");

int N;
vector< pair<double,double> > points;

double tri_area(pair<double, double> p1, pair<double,double> p2){

    return p1.first * p2.second - p2.first * p1.second;
}

double find_area(){
    double area = 0;
    for(int i = 0; i < N-1; i++){
        area += tri_area(points[i],points[i+1]);
    }
    area += tri_area(points[N-1], points[0]);
    return abs(area)/2;
}

int main(){
    fin >> N;
    double x, y;
    for(int i = 0; i < N; i++){
        fin >> x >> y;
        points.push_back(make_pair(x,y));
    }
    fout << std::setprecision(5) << std::fixed << find_area() << "\n";
    return 0;
}

SECOND:

#include <iostream>
#include <vector>
#include <stdlib.h>
#include <iomanip> 
#include <cmath>
#include <cstdio>
#define max 1000000
using namespace std;

int N;
vector< pair<double,double> > points;

double tri_area(pair<double, double> p1, pair<double,double> p2){

    return p1.first * p2.second - p2.first * p1.second;
}

double find_area(){
    double area = 0;
    for(int i = 0; i < N-1; i++){
        area += tri_area(points[i],points[i+1]);
    }
    area += tri_area(points[N-1], points[0]);
    return abs(area/2.);
}

int main(){
    freopen("aria.in","r",stdin);
    freopen("aria.out","w",stdout);
    scanf("%d",&N);
    double x, y;
    for(int i = 0; i < N; i++){
        scanf("%lf %lf",&x,&y);
        points.push_back(make_pair(x,y));
    }
    printf("%lf", find_area());
    return 0;
}
2
  • What is telling you time limit is exceeded? Have you checked that the second version is actually giving you the correct answer, and not just an answer? Apr 16, 2014 at 14:14
  • I submitted the problem on the site and the evaluation board tells me that the first one is slower than the second. But both are correct :) Apr 16, 2014 at 19:36

1 Answer 1

0

The main difference of these versions is

fin >> x >> y;

and

scanf("%lf %lf",&x,&y);

but not fstream vs printf that called ones from the end of program.

The difference is that C++-streams are synchronized with C-streams and this is reduces their speed. If you know, that you'll never mix fstream and FILE* in your program, you can switch off this synchronization by calling sync_with_stdio like this:

std::ios::sync_with_stdio(false);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.