jeudi 26 décembre 2019

Iterator for loop in map

I tried the following code but i am not able to find the error. The error is in the loop section but I can not figure out that how to correctly use the iterator in order to avoid the errors. Please help and please clarify my concepts. The problem statement is https://codeforces.com/contest/268/problem/A. I have solved it via vector

    int main()
    {
        std::ios::sync_with_stdio(false);
        int n,x,y,count=0; cin>>n;
        std::vector<pair<int,int>> v;
        for (int i = 0; i < n; ++i)
        {
            cin>>x>>y;
            v.push_back(make_pair(x,y));
        }

        for (int i = 0; i < n; ++i)
        {
            for (int j=i+1; j < n; ++j)
            {
                if(v[i].f==v[j].s){
                    count++;
                }
                if(v[i].s==v[j].f){
                    count++;
                }
            }
        }
        cout<<count;


        return 0;
    }

but having problem via map. It gives SIGTSTP error when using map.

#include <iostream>
#include <map>

using std::cin;
using std::cout;
using std::make_pair;

int main() {
  std::ios::sync_with_stdio(false);
  int n, x, y, count = 0;
  cin >> n;
  std::map<int, int> m;
  for (int i = 0; i < n; ++i) {
    cin >> x >> y;
    m.insert(make_pair(x, y));
  }

  for (auto i = m.begin(); i != m.end(); ++i) {
    for (auto j = ++i; j != m.end(); ++j) {
      if (i->first == j->second) {
        count++;
      }
      if (i->second == j->first) {
        count++;
      }
    }
  }
  cout << count;
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire