0

There's in output Give me 0 0

#include <bits/stdc++.h>
#define fsv(i , n)  for(int i = 0 ; i < n ; ++i)
using namespace std;

int main()
{
 int n ;
 cin >> n ;
 vector< pair< int , pair<int, int> > > vp(n);
 vector <int> v(n) ;

 fsv(i , v.size())cin >> v[i];

  for(int i = 0 ; i < n ; ++i){
     for(int j = i+1 ; j < n-1 ; ++j){
        vp.push_back(make_pair(abs(v[i]-v[j]) , make_pair(i,j)));
     }
  }
 sort(vp.begin() , vp.end());

 cout << vp[0].second.first << " " << vp[0].second.second;

}

this code related by code forces problem , i know that there's other ways ... but i'm asking this is proper way to access elements like that ?! http://codeforces.com/contest/34/problem/A

max66
  • 65,235
  • 10
  • 71
  • 111
  • 4
    Please don't do this: `#define fsv(i , n)` - it really doesn't make your code easier to read or follow, on the contrary: now I have to think harder when reading it. Generally speaking in C++ avoid preprocessor macros wherever possible - and especially avoid them for control-flow statements. – Dai Sep 16 '18 at 21:19
  • Alternatively, `std::tuple` as of C++11. – Eljay Sep 16 '18 at 21:24
  • `vector< pair< int , pair > > vp(n);` creates a vector that is filled with `n` default initialized elements. I wouldn't be surprised if one of those ends up being the first element after the `sort` – UnholySheep Sep 16 '18 at 21:24
  • Also [don't `#include `](https://stackoverflow.com/q/31816095/2069064) – Barry Sep 16 '18 at 21:44

1 Answers1

2

The problem is that

vector< pair< int , pair<int, int> > > vp(n);
// ......................................^^^  n initial elements

initialize a vector with n elements and with push_back() you add other n elements`.

After sorting v, the v[0] element is (I suppose) one of the initials n.

You should create an empty vector

vector< pair< int , pair<int, int> > > vp;
// ....................................^^  no more initial elements; empy!

and, just to speed up and avoid a superfluous relocations, reserve n as size (but ins't necessary)

vp.reserve(n);

before pushing back n elements.

Off Topic suggestion: please, avoid including a not-standard header as

#include <bits/stdc++.h>
max66
  • 65,235
  • 10
  • 71
  • 111
  • I appreciated your help ... thanks a lot , but we always in competitive programming contest find the fastest way and the least words (" i mean the code") to make it make fit in time and to get more rank – Amir Haytham Salama Sep 16 '18 at 23:47
  • @AmirHaytham - It's the reason because I don't like competitive programming. I like good programs, not fast developed ones. – max66 Sep 17 '18 at 00:32