jeudi 14 novembre 2019

Loosing content of 2D vector when passing by reference

I am solving a problem, but I have run into an error which is odd. In the eval function I recieve scores as a reference to a 2d vector. For the first many calls to eval the content of scores is preserved. However at some point the content of a subvector (vector<int>) in scores is lost - the size() of the subvector is 0. When I however change the code to recieve scores as a copy (new instance of the vector) I do not run into the problem but obviously the code will be way to slow. Like this:

...
int eval(vector<int>&team, vector<vector<int>> scores){
...
void rec(int idx, int d, vector<int>& team, vector<vector<int>> scores){
...

The problem occurs with the following test-data.

22 6 2000
0 0 0 1 0 0
0 0 0 0 0 1
0 9 0 0 0 0
6 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 10 0
0 6 0 0 0 0
0 0 1 0 0 0
2 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 10
0 0 10 0 0 0
0 0 0 0 1 0
0 0 0 10 0 0
6 0 0 0 0 0
1 0 0 0 0 0
0 5 0 0 0 0
0 6 0 0 0 0
1 0 0 0 0 0
10 0 0 0 0 0
0 10 0 0 0 0
0 4 0 0 0 0

Here is all the code. I hope you can help med resolve this and provide som insight as to why this error might occur. Also this is my first post on stackoverflow (let me know if I could have improved the post in any way :)).

#include<bits/stdc++.h>
using namespace std;
int N, K, C;
vector<int> teams;
int eval(vector<int>&team, vector<vector<int>>& scores){
  int s = 0;
  for(int i = 0; i < K; i++){
    int m = 0;
    for(int j = 0; j < K; j++){
      cout << team[j] << scores[team[j]].size() << " " << i << endl;
      m = max(scores[team[j]][i], m);
    }
    s += m;
  }
  return s;
}
void rec(int idx, int d, vector<int>& team, vector<vector<int>>& scores){
  if(d == K){
    teams.push_back(eval(team, scores));
  }
  for(int i = idx; i < N; i++){
    team[d] = i;
    rec(i+1, d+1, team, scores);
  }
}
int main(){
  cin >> N >> K >> C;
  vector<vector<int>> scores = vector<vector<int>> (N, vector<int> (K, 0));
  for(int i = 0; i < N; i++){
    for(int j = 0; j < K; j++){
      cin >> scores[i][j];
    }
  }
  //for(int i = 0; i < N; i++) cout << i << " "<< scores[i].size() << endl;
  vector<int> team (K);
  rec(0, 0, team, scores);
  sort(teams.rbegin(), teams.rend());
  cout << teams[C-1] << endl;
}

Aucun commentaire:

Enregistrer un commentaire