TLE in Wormholes (ZCO12002)

Following is the link to my submission of problem “Wormholes”.
https://www.codechef.com/viewsolution/31992312

My submission is working fine for sub task.

According to constraint i.e. (10^5), solution may work for O(NlogN) and i think my solution is satisfying this complexity.
Please suggest me if i am wrong.

You need to pass the vector by reference. Here’s the working code :


// Wormholes
// Author: shubh_singh
#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <chrono>
#include <complex>
#define endl "\n"
#define ll long long int
#define vi vector<int>
#define vll vector<ll>
#define vvi vector < vi >
#define pii pair<int,int>
#define pll pair<long long, long long>
#define mod 1000000007
#define inf 1000000000000000001;
#define all(c) c.begin(),c.end()
#define mp(x,y) make_pair(x,y)
#define mem(a,val) memset(a,val,sizeof(a))
#define rep(i,n) for(int i=0;i<(n);i++)
#define eb emplace_back
#define pb push_back
#define f first
#define s second
using namespace std;

int next(vi &v, int val) {
	int start = 0;
	int end = v.size();
	int size = end;
	int ans = -1;
	while (start <= end) {
		int mid = (start + end) / 2;
		if(mid < 0 || mid >= size)
			break;
		if (v[mid] == val)
			return v[mid];
		else if (v[mid] <= val)
			start = mid + 1;
		else {
			ans = mid;
			end = mid - 1;
		}
	}
	return (ans == -1) ? -1 : v[ans];
}
 
int prev(vi &v, int val) {
	int start = 0;
	int end = v.size();
	int size = end;
	int ans = -1;
	while (start <= end) {		
		int mid = (start + end) / 2;
		if(mid < 0 || mid >= size)
			break;			
		if (v[mid] == val)
			return v[mid];
		else if (v[mid] >= val)
			end = mid - 1;
		else {
			ans = mid;
			start = mid + 1;
		}
	}
	return (ans == -1) ? -1 : v[ans];
}
int main() {
	std::ios::sync_with_stdio(false);
	int n, x, y;
	cin >> n >> x >> y;
	vector<pii> v(n);
	rep(i, n)
	cin >> v[i].f >> v[i].s;
	vi wormholeV(x);
	rep(i, x)
	cin >> wormholeV[i];
	vi wormholeW(y);
	rep(i, y)
	cin >> wormholeW[i];
	sort(all(wormholeV));
	sort(all(wormholeW));
	int minVal = INT_MAX;
	for (auto it : v) {
		int first = prev(wormholeV, it.f);
		int last = next(wormholeW, it.s);
		if (last >= 0 && first >= 0)
			minVal = min(minVal, (last - first + 1));
	}
	cout << minVal;
	return 0;
}

Can you please explain, why passing vector by reference is necessary? Because i don’t think it is necessary as i am not updating values of vector. (I have not submitted code yet, waiting for reply) :slight_smile:

If you don’t pass it by reference, it creates a new vector by copying the vector that you just passed in the function which was causing the TLE.

Thanks shreeyas! I will keep this thing in mind in future too :innocent: