Here is the code,problem link-“https://www.codechef.com/problems/MAGICHF”
#include <stdio.h>
int main()
{
int t,i;
scanf("%d",&t);
for(i=0;i<t;i++)
{
int s,n,x,j,a,b;
scanf("%d %d %d",&n,&x,&s);
for(j=0;j<s;j++)
{
scanf("%d %d",&a,&b);
if(a==x&&b<=n)
{
x=b;
}
else if(b==x&&a<=n)
{
x=a;
}
}
printf("%d",x);
}
return 0;
}