SPOJ.com - Problem KOIREP

  #include<bits/stdc++.h>
using namespace std;
int main()
{
	long n,m;
	cin>>n>>m;
	vector <pair <long,long > > V;
	for(long i=0;i<n;i++)
	{
		for(long j=0;j<m;j++)
		{
			long x;
			cin>>x;
			V.push_back({x,i+1});
		}
	}
	sort(V.begin(),V.end());
/*	for(long j=0;j<m*n;j++)
	{
		cout<<V[j].first<<" "<<V[j].second<<"  ";
	}
	cout<<endl;*/
			vector <long> count(n+1,0);long c=1;
	long left=0;
	long right=0;long res,min=100000000;
	count[V[right].second]++;
/*	cout<<V[left].first<<" "<<V[left].second<<endl;
	cout<<V[right].first<<" "<<V[right].second<<endl;
	*/
	while(left<m*n)
	{
		
		while(right<m*n && c!=n)
		{
			right++;
			if(right!=m*n)
			{
				long temp=count[V[right].second];
				count[V[right].second]++;
				if(temp==0 && count[V[right].second]==1)
				c++;
			}
			else
			break;
			
		}
	//	cout<<c<<endl;
//		cout<<"left: "<<left<<endl;
//		cout<<"right: "<<right<<endl;
		if(right==m*n)
		break;
		if(c==n)
		{
			res=V[right].first-V[left].first;
			if(res<min)
			{
				min=res;
			}
		}
	
		long temp2=count[V[left].second];
	//	cout<<temp2<<endl;
		count[V[left].second]--;
	//	cout<<count[V[left].second]<<endl;
		if(temp2==1 && count[V[left].second]==0)
		c--;
	//	cout<<c<<endl;
		left++;		
	}
	cout<<min<<endl;
	

	return 0;
} ```
My code is giving wrong answer. What will be the answer for N=1 M=4  5 8 9 4?