wrong answer in RACELANE

I have tried all test cases i could think of but i am not able to find why it is giving wrong answer.please help.

#include<iostream>
using namespace std;
int main()
{
	int t,b,i,k;
	cin>>t;
	while(t--)
	{
		int len=0;
		int q[10][2];
		int r[501];
		for(i=0;i<501;i++)
			r[i]=0;
		for(i=0;i<10;i++)
			for(int j=0;j<2;j++)
				q[i][j]=0;
		cin>>b;
		int s,e,l;
		for(i=0;i<b;i++)
		{
			cin>>s>>e>>l;
			q[l][0]=s;
			q[l][1]=e;
		}
		for(i=0;i<9;i++)
		{
			if(q[i][0]==0 && q[i+1][0]==0)
				continue;
			if(q[i][1]>=q[i+1][0] && q[i][1]<=q[i+1][1] && q[i][0]<q[i+1][0])
			{
				for(k=q[i+1][0];k<=q[i][1];k++)
					if(r[k]==0)
					{
						len++;
						r[k]=1;
					}
			}
			else if(q[i+1][0]>=q[i][0] && q[i+1][0]<=q[i][1] && q[i+1][1]>q[i][1])
			{
				for(k=q[i][1];k<=q[i+1][0];k++)
					if(r[k]==0)
					{
						len++;
						r[k]=1;
					}
			}
			else if(q[i][0]<=q[i+1][0] && q[i][1]>=q[i+1][1])
			{
				for(k=q[i+1][0];k<=q[i+1][1];k++)
					if(r[k]==0)
					{
						len++;
						r[k]=1;
					}
			}
			else if(q[i][0]>=q[i+1][0] && q[i][1]<=q[i+1][1])
			{
				for(k=q[i][0];k<=q[i][1];k++)
					if(r[k]==0)
					{
						len++;
						r[k]=1;
					}
			}
		}
		cout<<500-len<<endl;
	}
	return 0;
}