Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
any help with optimizing following code to make it run faster.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class gfg
{
public:
bool satisfiable(std::vector<int> a, std::vector<int> b) {
  while (!a.empty()) {
    std::sort(b.begin(), b.end(), std::greater<int>());
    int k = a.back();
    a.pop_back();
    if (k > b.size()) return false;
    if (k == 0) continue;
    if (b[k - 1] == 0) return false;
    for (int i = 0; i < k; i++)
      b[i]--;
  }
  for (std::vector<int>::iterator i = b.begin(); i != b.end(); i++)
    if (*i != 0)
      return false;
  return true;
}

};


int main()
{
    gfg g;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int r,c,n,cnt=0;
    cin >> n;
    while(cnt<n){
        cnt++;
    cin >> r >> c;
    int x;
      vector<int> a;
      vector<int> b;
    for(int i=0;i<r;i++){
            cin >> x;
          a.push_back(x);
    }

    for(int j=0;j<c;j++){
          cin >> x;
          b.push_back(x);
    }



    if(g.satisfiable(a,b)) cout << "YES\n";
    else cout << "NO\n";
    }

    return 0;
}

Expected : Average 1s or less processing time per test case Actual : Average 2s to 2.5s processing time per test case

What I have tried:

Tried making function inline, tried cin.TIE(NULL), tried ios_base::sync_with_stdio(false);
Posted
Updated 31-May-19 13:48pm
Comments
Patrice T 31-May-19 19:09pm    
What is supposed to do the code ?
Give link to challenge

1 solution

Some quick thoughts:

In gfg::satisfiable(), vector b doesn't get re-ordered, so you don't need to sort each time through the while loop. You do decrement elemnts 0..k elements of b, but that won't change the sort order.

push_back() checks the current allocation of the vector and possibly re-allocates each time. Pre allocating the vector, and using direct element access will reduce the time taken to set up the vector:
C++
vector<int> a(r);
for(int i = 0; i < r; ++i)
    cin >> a[i];
This will help greatly if the number of inputs is large;

If possible read the entire input file in one go, and then use string processing to parse it. The input format is probably fairly simple, so it should be possible to write a parser that doesn't use the (possibly slow) iostream facility.

If you can't read the entire input file in one go, maybe you can use getline() to read some, or all, of the elements of the vector, then parse them out.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900