#include <iostream>
using namespace std;

int main() {
    int t, n,k;
    cin>>t;
    for(int i=0;i<t;i++){
        cin>>n>>k;
        if(n%2==0&&k%2==0&&n>=k){
            cout<<"yes"<<endl;
        }else if(n%2!=0&&k%2!=0&&n>=k){
            cout<<"yes"<<endl;
        }else{
            cout<<"no"<<endl;
        }

    }return 0;
}


#include <iostream>
using namespace std;

int main() {
    int t, n,k;
    cin>>t;
    for(int i=0;i<t;i++){
        cin>>n>>k;
        if(n%2==0&&k%2==0&&n>=k*k){
            cout<<"YES"<<endl;
        }else if(n%2!=0&&k%2!=0&&n>=k*k){
            cout<<"yes"<<endl;
        }else if(n==1&&k==1){
            cout<<"YES"<<endl;
        }
        else{
            cout<<"NO"<<endl;
        }

    }return 0;
}


#include <iostream>
using namespace std;

int main() {
    int t, n,k;
    cin>>t;
    for(int i=0;i<t;i++){
        cin>>n>>k;
        if(n%2==0&&k%2==0&&n>=k*k){
            cout<<"yes"<<endl;
        }else if(n%2!=0&&k%2!=0&&n>k*k){
            cout<<"yes"<<endl;
        }else if(n==1&&k==1){
            cout<<"yes"<<endl;
        }
        else{
            cout<<"no"<<endl;
        }

    }return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
        ll a,b;
        cin>>a>>b;
        if(a%2==0 && b%2==0 && b<=a/2)
        cout<<"YES"<<endl;
        else if(a%2!=0 && b%2!=0 && b<(a+1)/2)
        cout<<"YES"<<endl;
        else
        cout<<"NO"<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main(){
    long long int t,n,k,x;
    cin>>t;
    bool ok;
    while(t--){
        cin>>n>>k;
        //ok = false;
        if(n<(k*k)) ok = false;
        else{
        	x = n-(k*k);
        	if(x==0) ok = true;
        	else{
        	if(x%2==0) ok = true;
        	else ok = false;
        	}
		}
		if(ok) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
        ll a,b;
        cin>>a>>b;
        if(a%2==0 && b%2==0 && b<a*a)
        cout<<"YES"<<endl;
        else if(a%2!=0 && b%2!=0 && (b<a*a))
        cout<<"YES"<<endl;
        else
        cout<<"NO"<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
        ll a,b;
        cin>>a>>b;
        if(a%2==0 && b%2==0 && b<=a*a)
        cout<<"YES"<<endl;
        else if(a%2!=0 && b%2!=0 && b<=a*a)
        cout<<"YES"<<endl;
        else
        cout<<"NO"<<endl;
    }
    return 0;
}


[9:37 pm, 23/03/2020] Anudeep Sir Cse: #include <bits/stdc++.h>
using namespace std;

int main(){
    long long int t,n,k,x;
    cin>>t;
    bool ok;
    while(t--){
        cin>>n>>k;
        //ok = false;
        if(n<(k*k)) ok = false;
        else{
        	x = n-(k*k);
        	if(x==0) ok = true;
        	else{
        	if(x%2==0) ok = true;
        	else ok = false;
        	}
		}
		if(ok) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
        ll a,b;
        cin>>a>>b;
        if(a%2==0 && b%2==0 && b<a/2)
        cout<<"YES"<<endl;
        else if(a%2!=0 && b%2!=0 && b<(a+1)/2)
        cout<<"YES"<<endl;
        else
        cout<<"NO"<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
        ll a,b;
        cin>>a>>b;
        if(a%2==0 && b%2==0 && (b-a*a)%2==0)
        cout<<"YES"<<endl;
        else if(a%2!=0 && b%2!=0 && (b-a*a)%2==0)
        cout<<"YES"<<endl;
        else
        cout<<"NO"<<endl;
    }
    return 0;
}


n, a = input(), map(int, raw_input().split())
t = a.index(max(a))
s = list(reversed(a)).index(min(a))
c = t + s
print c - 1 if t >= n - s else c


num_entrada = int(raw_input())
alturas = [int(i) for i in raw_input().split()]
ordenada = alturas[:]
ordenada.sort()
cont = 0
for i in range(num_entrada):
	if alturas[-1] == ordenada[0]:
		break
	for j in range(num_entrada-2,-1,-1):
		if alturas[j] == ordenada[0] and alturas[j] < alturas[j+1] :
			alturas[j], alturas[j+1] = alturas[j+1], alturas[j]
			cont += 1
			break

for i in range(num_entrada):
	if alturas[0] == ordenada[-1]:
		break
	for j in range(1,num_entrada):
		if alturas[j] == ordenada[-1] and alturas[j] > alturas[j-1] :
			alturas[j], alturas[j-1] = alturas[j-1], alturas[j]
			cont += 1
			break

print cont


num_entrada = int(raw_input())
alturas = [int(i) for i in raw_input().split()]
ordenada = alturas[:]
ordenada.sort()
cont = 0
for i in range(num_entrada):
	for j in range(num_entrada-2,-1,-1):
		if alturas[j] == ordenada[0] and alturas[j] < alturas[j+1] :
			alturas[j], alturas[j+1] = alturas[j+1], alturas[j]
			cont += 1
			break
	if alturas[-1] == ordenada[0]:
		break

for i in range(num_entrada):
	for j in range(1,num_entrada):
		if alturas[j] == ordenada[-1] and alturas[j] > alturas[j-1] :
			alturas[j], alturas[j-1] = alturas[j-1], alturas[j]
			cont += 1
			break
	if alturas[0] == ordenada[-1]:
		break

print cont


height_soldier=[]
n=input()
for i in range(n):
    height_soldier.append(input())

#Finding the tallest and smallest soldier (nearest to their ends in case of similar heights)
tall,tall_position=0,0
small,small_position=10000,0
for i in range(n):
    if height_soldier[n-i-1]>=tall:
        tall,tall_position=height_soldier[n-i-1],n-i-1
    if height_soldier[i]<=small:
        small,small_position=height_soldier[i],i

if tall_position>small_position:
    swap=tall_position+n-small_position-1-1
else:
    swap=tall_position+n-small_position-1
print swap


height_soldier=[]
n=input()
for i in range(n):
    height_soldier.append(input())

#Finding the tallest and smallest soldier (nearest to their ends in case of similar heights)
tall,tall_position=0,0
small,small_position=10000,0
for i in range(n):
    if height_soldier[n-i-1]>=tall:
        tall,tall_position=height_soldier[n-i-1],n-i-1
    if height_soldier[i]<=small:
        small,small_position=height_soldier[i],i

"""No. of swaps required, 1 swap is reduced when the tallest and smallest soldier cross their paths"""
if tall_position>small_position:
    swap=tall_position+n-small_position-1-1
else:
    swap=tall_position+n-small_position-1
print swap


n=input()
height_soldier = map(int,raw_input().split())

#Finding the tallest and smallest soldier (nearest to their ends in case of similar heights)
tall,tall_position=0,0
small,small_position=10000,0
for i in range(n):
    if height_soldier[n-i-1]>=tall:
        tall,tall_position=height_soldier[n-i-1],n-i-1
    if height_soldier[i]<=small:
        small,small_position=height_soldier[i],i

if tall_position>small_position:
    swap=tall_position+n-small_position-1-1
else:
    swap=tall_position+n-small_position-1
print swap


height_soldier=[]
n=input("Enter the no. of soldiers: ")
for i in range(n):
    height_soldier.append(input())

#Finding the tallest and smallest soldier (nearest to their ends in case of similar heights)
tall,tall_position=0,0
small,small_position=10000,0
for i in range(n):
    if height_soldier[n-i-1]>=tall:
        tall,tall_position=height_soldier[n-i-1],n-i-1
    if height_soldier[i]<=small:
        small,small_position=height_soldier[i],i

print tall,tall_position, small, small_position

"""No. of swaps required, 1 swap is reduced when the tallest and smallest soldier cross their paths"""
if tall_position>small_position:
    swap=tall_position+n-small_position-1-1
else:
    swap=tall_position+n-small_position-1
print "Swaps: "+str(swap)


import time
def testRawInput():
	while 1:
		try:
			print 'Input a integer number between 1 and 100: '
			number = int( raw_input() )
			if number < 0 or number > 100:
				print 'Input not acceptable. Try agein...'
			else:
				break
		except ValueError:
			print 'You\'re wrong. Try again...'
	while 1:
		try:
			print 'Input', number, 'integer seperated by single white space:'
			input_string = raw_input()
			input_string = input_string.split(' ')
			for i in range(len(input_string)):
				input_string[i] = int(input_string[i])
			if len(input_string) == number:
				break
		except NumberFormatError:
			print 'You must input', n, 'integer seperated by single white space'
			print 'Try again...'
	return input_string

def minSec():
	input_list = testRawInput()
	start = time.time()
	length = len(input_list)
	max_index = 0
	max_value = input_list[0]
	for i in range(length)[1:]:
		if max_value < input_list[i]:
			max_value = input_list[i]
			max_index = i
	min_index = length - 1
	min_value = input_list[length-1]
	for i in range(length-1, 0, -1):
		if min_value > input_list[i]:
			min_value = input_list[i]
			min_index = i
	result = max_index + length - min_index - 1
	if max_index < min_index:
		return result
	else:
		return result - 1
def main():
	print minSec()

if __name__ == '__main__':
		main()


def testRawInput():
	number = int( raw_input() )
	input_string = raw_input()
	input_string = input_string.split(' ')
	for i in range(len(input_string)):
		input_string[i] = int(input_string[i])
	return input_string

def minSec():
	input_list = testRawInput()
	length = len(input_list)
	if length == 1:
		return 0
	max_index = 0
	max_value = input_list[0]
	for i in range(length)[1:]:
		if max_value < input_list[i]:
			max_value = input_list[i]
			max_index = i
	min_index = length - 1
	min_value = input_list[length-1]
	for i in range(length-1, 0, -1):
		if min_value > input_list[i]:
			min_value = input_list[i]
			min_index = i
	result = max_index + length - min_index - 1
	if max_index < min_index:
		return result
	else:
		return result - 1
def main():
	print minSec()

if __name__ == '__main__':
		main()


def testRawInput():
	number = int( raw_input() )
	input_string = raw_input()
	input_string = input_string.split(' ')
	for i in range(len(input_string)):
		input_string[i] = int(input_string[i])
	return input_string

def minSec():
	input_list = testRawInput()
	length = len(input_list)
	if length <= 2 or length > 100:
		return 0
	max_index = 0
	max_value = input_list[0]
	for i in range(length)[1:]:
		if max_value < input_list[i]:
			max_value = input_list[i]
			max_index = i
	min_index = length - 1
	min_value = input_list[length-1]
	for i in range(length-1, -1, -1):
		if min_value > input_list[i]:
			min_value = input_list[i]
			min_index = i
	result = max_index + length - min_index - 1
	if max_index < min_index:
		return result
	else:
		return result - 1
def main():
	print minSec()

if __name__ == '__main__':
		main()


import sys
def testRawInput():
	number = int( raw_input() )
	input_string = raw_input()
	input_string = input_string.split(' ')
	for i in range(len(input_string)):
		input_string[i] = int(input_string[i])
	if len(input_string) != number:
		sys.exit(1);
	return [input_string, number]

def minSec():
	[input_list, length] = testRawInput()
	if length == 2:
		if input_list[0] >= input_list[1]:
			return 0
		else:
			return 1
	max_index = 0
	max_value = input_list[0]
	for i in range(length)[1:]:
		if max_value < input_list[i]:
			max_value = input_list[i]
			max_index = i
	min_index = length - 1
	min_value = input_list[length-1]
	for i in range(length-1, -1, -1):
		if min_value > input_list[i]:
			min_value = input_list[i]
			min_index = i
	result = max_index + length - min_index - 1
	if max_index < min_index:
		return result
	else:
		return result - 1
def main():
	print minSec()

if __name__ == '__main__':
		main()


def testRawInput():
	number = int( raw_input() )
	input_string = raw_input()
	input_string = input_string.split(' ')
	for i in range(len(input_string)):
		input_string[i] = int(input_string[i])
	return input_string

def minSec():
	input_list = testRawInput()
	length = len(input_list)
	max_index = 0
	max_value = input_list[0]
	for i in range(length)[1:]:
		if max_value < input_list[i]:
			max_value = input_list[i]
			max_index = i
	min_index = length - 1
	min_value = input_list[length-1]
	for i in range(length-1, 0, -1):
		if min_value > input_list[i]:
			min_value = input_list[i]
			min_index = i
	result = max_index + length - min_index - 1
	if max_index < min_index:
		return result
	else:
		return result - 1
def main():
	print minSec()

if __name__ == '__main__':
		main()


n=input()
ls=list(map(int,raw_input().split()))
ls2=ls[:]
maxInd= ls.index(max(ls))
m=min(ls)
i=0
while m in ls:
    ls.pop(ls.index(m))
    i=i+1
minInd=ls2.index(m)+i-1
#print maxInd
#print minInd
if maxInd>minInd:
    print maxInd+(n-minInd-2)
else:
    print maxInd+(n-minInd-1)


n=input()
ls=list(map(int,raw_input().split()))
ls2=ls[:]
maxInd= ls.index(max(ls))
m=min(ls)
i=0
while m in ls:
    minInd=ls.index(m)
    ls.pop(ls.index(m))
    i=i+1
minInd=minInd+i-1
#print maxInd
#print minInd
if maxInd>minInd:
    print maxInd+(n-minInd-2)
else:
    print maxInd+(n-minInd-1)


l = int(raw_input())
s = map(int, raw_input().split())

min_index = 0
max_index = l-1

for i in xrange(l):
    if s[i] <= s[min_index]:
        min_index = i
    if s[i] > s[max_index]:
        max_index = i

# print l - min_index -1
# print max_index
res = (l - min_index -1) + max_index

if min_index < max_index:
    res -= 1

print res


l = int(raw_input())
s = map(int, raw_input().split())

min_index = 0
max_index = 0

for i in xrange(l):
    if s[i] <= s[min_index]:
        min_index = i
    if s[i] > s[max_index]:
        print max_index
        max_index = i

# print l - min_index -1
# print max_index
res = (l - min_index -1) + max_index

if min_index < max_index:
    res -= 1

print res


l = int(raw_input())
s = map(int, raw_input().split())

min_index = 0
max_index = 0

for i in xrange(l):
    if s[i] <= s[min_index]:
        min_index = i
    if s[i] > s[max_index]:
        # print max_index
        max_index = i

# print l - min_index -1
# print max_index
res = (l - min_index -1) + max_index

if min_index < max_index:
    res -= 1

print res


n=int(raw_input())
x=raw_input().split()
p=x.index(max(x))
x.reverse()
q=n-x.index(min(x))-1
if p<q:
    print p + (n - 1 - q)
elif p==q:
    print 0
else:
    print p + (n-1 - q) - 1


n=int(raw_input())
x=raw_input().split()
x=map(int,x)
p=x.index(max(x))
x.reverse()
q=n-x.index(min(x))-1
if p<q:
    print p + (n - 1 - q)
elif p==q:
    print 0
else:
    print p + (n-1 - q) - 1


n=int(raw_input())
x=raw_input().split()
x=map(int,x)
p=x.index(max(x))
x.reverse()
q=n-x.index(min(x))-1
print p,q
if p<q:
    print p + (n - 1 - q)
elif p==q:
    print 0
else:
    print p + (n-1 - q) - 1


n=int(raw_input())
x=raw_input().split()
p=x.index(max(x))
x.reverse()
q=n-x.index(min(x))
if p>q:
    print p+(n-q)-1
elif p==q:
    print 0
else:
    print p+(n-q)


def solve(n,hights):
    maxVal = heights[0]
    maxValIdx = 0
    minVal = hights[n-1]
    minValIdx = n-1

    for i in xrange(0,n):
        if heights[i] > maxVal:
            maxVal = hights[i]
            maxValIdx = i

        if heights[i] <= minVal:
            minVal = heights[i]
            minValIdx = i

    swaps = maxValIdx
    swaps +=(n-1) - minValIdx

    if maxValIdx > minValIdx:
        swaps -=1

    return swaps

if __name__ = "__main__":
    n = int(raw_input())
    height = map(int,raw_input().split(" "))
    print solve(n,heights)


def solve(n, heights):

    maxVal = heights[0]
    maxValIdx = 0
    minVal = heights[n-1]
    minValIdx = n-1

    for i in xrange(0, n):
        if heights[i] > maxVal:
            maxVal = heights[i]
            maxValIdx = i

        if heights[i] <= minVal:
            minVal = heights[i]
            minValIdx = i

    swaps = maxValIdx
    swaps += (n - 1) - minValIdx

    if maxValIdx > minValIdx:
        swaps -= 1

    return swaps

if __name__ == "__main__":

    n = int(raw_input())
    heights = map(int,raw_input().split(" "))
    print solve(n, heights)


n = int(raw_input())
l = map(int, raw_input().split())
high = max(l)
low = min(l)
lowIndex = l[::-1].index(low)
highIndex = l.index(high)
minSeconds = lowIndex + highIndex
if highIndex >= lowIndex:
    minSeconds-=1
print minSeconds


n = int(raw_input())
l = map(int, raw_input().split())
high = max(l)
low = min(l)
#print high
#print low
lowIndex = l[::-1].index(low)
highIndex = l.index(high)
minSeconds = lowIndex + highIndex
#print highIndex
#print lowIndex
if highIndex != lowIndex:
    minSeconds-=1
if len(l) <=2 and lowIndex <= highIndex:
    minSeconds-=1

print minSeconds


n = int(raw_input())
l = map(int, raw_input().split())
high = max(l)
low = min(l)
lowIndex = l[::-1].index(low)
highIndex = l.index(high)
minSeconds = lowIndex + highIndex
if highIndex > lowIndex:
    minSeconds-=1
if len(l) <=2 and lowIndex <= highIndex:
    minSeconds-=1

print minSeconds


n = int(raw_input())
l = map(int, raw_input().split())
high = max(l)
low = min(l)
lowIndex = l[::-1].index(low)
highIndex = l.index(high)
minSeconds = lowIndex + highIndex
if highIndex > lowIndex:
    minSeconds-=1
print minSeconds


n = int(raw_input())
l = map(int, raw_input().split())
lowIndex = l[::-1].index(min(l))
highIndex = l.index(max(l))
minSeconds = lowIndex + highIndex
if minSeconds >= n:
    minSeconds-=1
print minSeconds


n = int(raw_input())
l = map(int, raw_input().split())
high = max(l)
low = min(l)
print high
print low
lowIndex = l[::-1].index(low)
highIndex = l.index(high)
minSeconds = lowIndex + highIndex
print highIndex
print lowIndex
if highIndex != lowIndex:
    minSeconds-=1
if len(l) <=2 and lowIndex <= highIndex:
    minSeconds-=1

print minSeconds


n = int(raw_input())

a_n = map(int, raw_input().split())

a_max = max(a_n)
a_min = min(a_n)

a_max_index = a_n.index(a_max)
a_n.remove(a_max)

a_min_index = a_n.index(a_min)

a_min_count = a_n.count(a_min)

a_min_index = a_min_index + a_min_count -1

print a_max_index + n - a_min_index - 2


n = int(raw_input())

a_n = map(int, raw_input().split())

a_max_index = a_n.index(max(a_n))
a_min = min(a_n)
a_min_index = 0
a_n.remove(max(a_n))

if len(a_n) != 0:
	a_n.reverse()
	a_min_index = a_n.index(a_min)

print a_max_index + a_min_index


n = int(raw_input())

a_n = map(int, raw_input().split())

a_max = max(a_n)
a_min = min(a_n)

a_max_index = a_n.index(max(a_n))
a_min_index = a_n.index(min(a_n))

a_min_count = a_n.count(a_min)

a_min_index = a_min_index + a_min_count -1

print a_max_index + n - a_min_index - 1


n = input()
x = map(int , raw_input().split())
m = 0
i = 0
j = 0
mx = -34
mi = x[0]
while(j<n):
    if(mx<x[j]):
        m = j
    if(mi > x[j] or mi==x[j]):
        i = j
    j += 1
s = n-2-i+m
print s


n = input()
x = map(int , raw_input().split())
m = 0
i = 0
j = 0
mx = -34
mi = x[0]
while(j<n):
    if(mx<x[j]):
        m = j
        mx = x[j]
    if(mi >= x[j]):
        i = j
        mi = x[j]
    j += 1
if(m>i):
    s = -1
s = n-1-i+m
if(m>i):
    print s-1
else:
    print s


n = input()
x = map(int , raw_input().split())
m = 0
i = 0
j = 0
mx = -34
mi = x[0]
while(j<n):
    if(mx<=x[j]):
        m = j
    if(mi > x[j] or mi==x[j]):
        i = j
    j += 1
s = n-2-i+m
print s


n = input()
s = map(int, raw_input().split())
maxi = max(s)
mini = min(s)
for i in range(0, n):
    if s[i] == maxi:
        x = i+1
        break
sr = s[::-1]
for i in range(0, n):
    if s[i] == mini:
        y = i+1
print (x-1)+len(s)-y


n = input()
s = map(int, raw_input().split())
maxi = max(s)
mini = min(s)
for i in range(0, n):
    if s[i] == maxi:
        x = i+1
        break
sr = s[::-1]
for i in range(0, n):
    if s[i] == mini:
        y = i+1
if x > y:
    print x-1+len(s)-y-1
else:
    print x-1+len(s)-y


n = input()
s = map(int, raw_input().split())
maxi = max(s)
mini = min(s)
for i in range(0, n):
    if s[i] == maxi:
        x = i+1
        break
sr = s[::-1]
for i in range(0, n):
    if s[i] == mini:
        y = i+1
print x, y
if x > y:
    print x-1+len(s)-y-1
else:
    print x-1+len(s)-y


import sys
import traceback

def solve():
  n = map( eval, sys.stdin.readline().strip('\n\r ').split())
  hs = map( eval, sys.stdin.readline().strip('\n\r ').split())
  imx = 0
  imn = 0
  for i,h in enumerate(hs):
    if h > hs[imx]: imx = i
    if h <= hs[imn]: imn = i
  ans = imx + (n[0]-(imn+1))
  if imn<imx: ans += 1
  print ans

if __name__=="__main__":
  solve()


import sys
import traceback

def solve():
  n = map( eval, sys.stdin.readline().strip('\n\r ').split())
  hs = map( eval, sys.stdin.readline().strip('\n\r ').split())
  imx = 0
  imn = 0
  for i,h in enumerate(hs):
    if h >= hs[imx]: imx = i
    if h < hs[imn]: imn = i
  ans = imx + (n[0]-(imn+1))
  if imn<imx: ans += 1
  print ans

if __name__=="__main__":
  solve()


import sys
import traceback

def solve():
  n = map( eval, sys.stdin.readline().strip('\n\r ').split())
  hs = map( eval, sys.stdin.readline().strip('\n\r ').split())
  imx = 0
  imn = 0
  for i,h in enumerate(hs):
    if h > hs[imx]: imx = i
    if h <= hs[imn]: imn = i
  ans = imx + (n[0]-(imn+1))
  if imn<imx: ans -= 1
  print( ans )

if __name__=="__main__":
  solve()


n = int(raw_input())
arr = (map(int, raw_input().split(" ")))

max_i = 0
min_i = 0

max_a = arr[0]
min_a = arr[0]
for i in xrange(1,len(arr)):
    if arr[i] > max_a:
        max_i = i
        max_a = arr[i]
    if arr[i] <= min_a:
        min_i = i
        min_a = arr[i]

print abs(max_i) + abs(n - min_i - 1) - (1 if min_i < max_i else 0)


n = int(raw_input())
arr = (map(int, raw_input().split(" ")))

max_i = arr.index(max(arr))

max_steps = max_i

max_val = arr.pop(max_i)

arr.insert(0, max_val)

min_i = arr.index(min(arr))

min_steps = abs(n-1-min_i)

print max_steps + min_steps -1


n = int(raw_input())
arr = (map(int, raw_input().split(" ")))

def get_max_i(arr):
    m = 0
    for i in xrange(1, len(arr)):
        if arr[i] > arr[m]:
            m = i
    return m

def get_min_i(arr):
    m = len(arr) - 1
    for i in reversed(xrange(1, len(arr))):
        if arr[i] < arr[m]:
            m = i
    return m

if (get_max_i(arr) == 0 and get_min_i(arr) == n-1) or (arr[get_max_i(arr)] == arr[0] and arr[get_min_i(arr)] == arr[n-1]):
    print 0
else:
    max_i = get_max_i(arr)

    max_steps = max_i

    max_val = arr.pop(max_i)

    arr.insert(0, max_val)

    min_i = get_min_i(arr)

    min_steps = abs(n-1-min_i)

    count = max_steps + min_steps

    if get_min_i(arr) == 1 and len(arr) > 2:
        count -= 1

    print count


n = int(raw_input())
arr = (map(int, raw_input().split(" ")))

max_i = arr.index(max(arr))

max_steps = max_i

max_val = arr.pop(max_i)

arr.insert(0, max_val)

min_i = arr.index(min(arr))

min_steps = abs(n-1-min_i)

count = max_steps + min_steps

if arr.index(min(arr)) == 1:
	count -= 1

print count


n = int(raw_input())
arr = (map(int, raw_input().split(" ")))

def get_max_i(arr):
	m = 0
	for i in xrange(1, len(arr)):
		if arr[i] > arr[m]:
			m = i
	return m

def get_min_i(arr):
	m = 0
	for i in xrange(1, len(arr)):
		if arr[i] < arr[m]:
			m = i
	return m

if (get_max_i(arr) == 0 and get_min_i(arr) == n-1) or (arr[get_max_i(arr)] == arr[0] and arr[get_min_i(arr)] == arr[n-1]):
	print 0
else:
	max_i = get_max_i(arr)

	max_steps = max_i

	max_val = arr.pop(max_i)

	arr.insert(0, max_val)

	min_i = get_min_i(arr)

	min_steps = abs(n-1-min_i)

	count = max_steps + min_steps

	if get_min_i(arr) == 1 and len(arr) > 2:
		count -= 1

	print count


n = int(raw_input())
arr = (map(int, raw_input().split(" ")))

max_i = arr.index(max(arr))

max_steps = max_i

max_val = arr.pop(max_i)

arr.insert(0, max_val)

min_i = arr.index(min(arr))

min_steps = abs(n-1-min_i)

count = max_steps + min_steps

if arr.index(min(arr)) == 1 and len(arr) > 2:
	count -= 1

print count


n=int(raw_input())
a=[0 for i in range(n)]
a=map(int,raw_input().split())
ans=0
for i in range(n):
    if a[i]==max(a):
        ans+=i
        break
for i in range(n):
    if a[n-1-i]==min(a):
        ans+=n-1-i
        break
print ans


n=int(raw_input())
a=[0 for i in range(n)]
a=map(int,raw_input().split())
ans=0
for i in range(n):
    if a[i]==max(a):
        ans+=i
        break
for i in range(n):
    if a[n-1-i]==min(a):
        if ans>n-1-i: ans-=1
        ans+=n-1-i
        break
print ans


n=int(raw_input())
a=[0 for i in range(n)]
a=map(int,raw_input().split())
ans=0
for i in range(n):
    if a[i]==max(a):
        ans+=i
        break
for i in range(n):
    if a[n-1-i]==min(a):
        ans+=i
        break
print ans


n=int(raw_input())
a=[0 for i in range(n)]
a=map(int,raw_input().split())
ans=0
for i in range(n):
    if a[i]==max(a):
        ans+=i
        break
for i in range(n):
    if a[n-1-i]==min(a):
        if ans>n-1-i: ans-=1
        ans+=i
        break
print ans


L=input()
m=map(int,raw_input().split())
q=m.index(max(m))+m[::-1].index(min(m))
print q-[0,1][q>=L]


n=input()
l = map(int,raw_input().split())
mx,mxind = l[0],0
for i in range(1,n):
    if(l[i]>mx):
        mxind = i
        mx = l[i]
mn,mnind = l[0],0
for i in range(1,n):
    if(l[i]<=mn):
        mnind = i
        mn = l[i]

ans = mxind + (n-mnind-1)
print ans if mnind>mxind else ans-1


a = raw_input()
b = map(int,raw_input().split())
maxer= b.index(max(b))
miner= b.index(min(b))
total = 0
storage = 0
if b.count(min(b)) ==1:
    if miner>maxer:
        total = maxer + len(b) - miner -2
    else:
        total = maxer + len(b) - miner - 1
else:
   while miner < len(b):
       if b[miner] == min(b):
           storage = miner
       miner +=1
   if miner>maxer:
        total = maxer + len(b) - storage -2
   else:
        total = maxer + len(b) - storage - 1

print total


a = raw_input()
b = map(int,raw_input().split())
maxer= b.index(max(b))
miner= b.index(min(b))
total = 0
storage = 0
if b.count(min(b)) ==1:
    total = maxer +len(b)- miner -2
else:
   while miner < len(b):
       if b[miner] == min(b):
           storage = miner
       miner +=1
total = maxer + len(b) - storage -2

print total


a = raw_input()
b = map(int,raw_input().split())
maxer= b.index(max(b))
miner= b.index(min(b))
total = 0
storage = 0
if b.count(min(b)) ==1:
    if mine<maxer:
        total = maxer + len(b) - miner -2
    else:
        total = maxer + len(b) - miner - 1
else:
   while miner < len(b):
       if b[miner] == min(b):
           storage = miner
       miner +=1
   if miner<maxer:
        total = maxer + len(b) - storage -2
   else:
        total = maxer + len(b) - storage - 1

print total


a = raw_input()
b = map(int,raw_input().split())
maxer= b.index(max(b))
miner= b.index(min(b))
total = 0
storage = 0
if b.count(min(b)) ==1:
    if maxer >miner:
       total = maxer +len(b)- miner -2
    else:
       total = maxer + len(b)-miner - 1
else:
   while miner < len(b):
       if b[miner] == min(b):
           storage = miner
       miner +=1
   if maxer> storage:
       total = maxer + len(b) - storage -2
   else:
       total = maxer + len(b) - storage -1

print total


a = raw_input()
b = map(int,raw_input().split())
maxer= b.index(max(b))
miner= b.index(min(b))
total = 0
storage = 0
if b.count(min(b)) ==1:
    if mine<maxer:
        total = maxer + len(b) - miner -2
    else:
        total = maxer + len(b) - miner - 1
else:
   while miner < len(b):
       if b[miner] == min(b):
           storage = miner
       miner +=1
if miner<maxer:
    total = maxer + len(b) - storage -2
else:
    total = maxer + len(b) - storage - 1

print total


a = raw_input()
b = map(int,raw_input().split())
print b
maxer= b.index(max(b))
miner= b.index(min(b))
total = 0
storage = 0
if b.count(min(b)) ==1:
    total = maxer +len(b)- miner -2
else:
   while miner < len(b):
       if b[miner] == min(b):
           storage = miner
       miner +=1
total = maxer + len(b) - storage -2

print total


a = raw_input()
b = map(int,raw_input().split())
print b
maxer= b.index(max(b))
miner= b.index(min(b))
total = 0
storage = 0
if b.count(min(b)) ==1:
    if maxer >miner:
       total = maxer +len(b)- miner -2
    else:
       total = maxer + len(b)-miner - 1
else:
   while miner < len(b):
       if b[miner] == min(b):
           storage = miner
       miner +=1
   if maxer> storage:
       total = maxer + len(b) - storage -2
   else:
       total = maxer + len(b) - storage -1

print total


raw_input()
nums = map(int, (raw_input().split()))
nmax = 0
imax = 0
nmin = 111
imin = 0

for i in xrange(0, len(nums)):
	if nums[i] > nmax:
		nmax = nums[i]
		imax = i
	if nums[i] <= nmin:
		nmin = nums[i]
		imin = i

if imax > imin:
	print imax + (len(nums) - 1 - imin - 2)
else:
	print imax + (len(nums) - 1 - imin)


raw_input()
nums = map(int, (raw_input().split()))
nmax = 0
imax = 0
nmin = 111
imin = 0

for i in xrange(0, len(nums)):
	if nums[i] > nmax:
		nmax = nums[i]
		imax = i
	if nums[i] <= nmin:
		nmin = nums[i]
		imin = i

if imax > imin:
	print imax + (len(nums) - 1 - imin - 1)
else:
	print imax + (len(nums) - 1 - imin)


ans = 0
a = int(raw_input())
b = raw_input()
b = b.split()
temp = b
for i in range(a):
	b[i] = int(b[i])

high = max(b)
low = min(b)

high = b.index(high)
low_temp = b.index(low)
b.reverse()
low = b.index(low)

if low_temp<high:
	print low+high-1
else:
	print low+high


ans = 0
a = int(raw_input())
b = raw_input()
b = b.split()
temp = b
for i in range(a):
	b[i] = int(b[i])

high = max(b)
low = min(b)

high = b.index(high)
b.reverse()
low = b.index(low)

if high>=low:
	print high+low-1
else:
	print high+low


ans = 0
a = int(raw_input())
b = raw_input()
b = b.split()
temp = b
for i in range(a):
	b[i] = int(b[i])

high = max(b)
low = min(b)

high = b.index(high)
b.reverse()
low = b.index(low)
low_temp = a-low

if low_temp<high:
	print low+high-1
else:
	print low+high


ans = 0
a = int(raw_input())
b = raw_input()
b = b.split()
temp = b
for i in range(a):
	b[i] = int(b[i])

high = max(b)
low = min(b)

high = b.index(high)
b.reverse()
low = b.index(low)

if high>low:
	print high+low-1
else:
	print high+low


ans = 0
a = int(raw_input())
b = raw_input()
b = b.split()
temp = b
for i in range(a):
	b[i] = int(b[i])

high = max(b)
low = min(b)

high = b.index(high)
b.reverse()
low = b.index(low)
low_temp = a-low-1

if low_temp<high:
	print low+high-1
else:
	print low+high


n = int(raw_input())
t = list(raw_input().split(" "))

max_v = 0
max_i = 0
min_v = t[n-1]
min_i = 0

for i in range(0, n):
  if t[i] > max_v:
    max_v = t[i]
    max_i = i
  if t[i] <= min_v:
    min_v = t[i]
    min_i = i

print min_i, max_i

print abs(0 - max_i) + abs((n - 1) - min_i)


n = int(raw_input())
t = list(raw_input().split(" "))

max_v = 0
max_i = 0
min_v = t[n-1]
min_i = 0

for i in range(0, n):
  if t[i] > max_v:
    max_v = t[i]
    max_i = i
  if t[i] <= min_v:
    min_v = t[i]
    min_i = i

print abs(0 - max_i) + abs((n - 1) - min_i)


n = input()
a = map(int, raw_input().split())
b= a.index(max(a)) + a[::-1].index(min(a))
print b - ( b >= n)


def SwapLeft(arr,index):
    temp=arr[index-1]
    arr[index-1]=arr[index]
    arr[index]=temp

def SwapRight(arr,index):
    temp=arr[index+1]
    arr[index+1]=arr[index]
    arr[index]=temp

def GetMaxIndex(arr):
    max_indices=[]
    for i in range(n):
        if soldiers[i]==max(soldiers):
            max_indices.append(i)
    return max_indices[0]

def GetMinIndex(arr):
    min_indices=[]
    for i in range(n):
        if soldiers[i]==min(soldiers):
            min_indices.append(i)
    return min_indices[len(min_indices)-1]

n=int(input())

inp=raw_input().split()

soldiers=[]

for i in inp:
    soldiers.append(int(i))

max_index=GetMaxIndex(soldiers)
time=0

while True:
    min_index=GetMinIndex(soldiers)
    if max_index==0 and min_index==n-1:
        break
    if min_index!=n-1:
        SwapRight(soldiers,min_index)
        time+=1
    max_index=GetMaxIndex(soldiers)
    if max_index!=0:
        SwapLeft(soldiers,max_index)
        time+=1
    #print soldiers,max_index,min_index

print time


def SwapLeft(arr,index):
    temp=arr[index-1]
    arr[index-1]=arr[index]
    arr[index]=temp

def SwapRight(arr,index):
    temp=arr[index+1]
    arr[index+1]=arr[index]
    arr[index]=temp

def GetMaxIndex(arr):
    max_indices=[]
    for i in range(n):
        if soldiers[i]==max(soldiers):
            max_indices.append(i)
    return max_indices[len(max_indices)-1]

def GetMinIndex(arr):
    min_indices=[]
    for i in range(n):
        if soldiers[i]==min(soldiers):
            min_indices.append(i)
    return min_indices[len(min_indices)-1]

n=int(input())

inp=raw_input().split()

soldiers=[]

for i in inp:
    soldiers.append(int(i))

max_index=GetMaxIndex(soldiers)
time=0

while True:
    min_index=GetMinIndex(soldiers)
    if max_index==0 and min_index==n-1:
        break
    if min_index!=n-1:
        SwapRight(soldiers,min_index)
        time+=1
    max_index=GetMaxIndex(soldiers)
    if max_index!=0:
        SwapLeft(soldiers,max_index)
        time+=1

print time


#coding: utf-8
n = int(raw_input())

sol = map(int, raw_input().split())

maior = 0
menor = 0
cont = 0
if max(sol) == sol[0] and min(sol) == sol[-1]:
	print 0
else:
	for i in range(len(sol)-1, -1, -1):
		if sol[i] == max(sol):
			maior = i
			#break

	for i in range(maior, 0, -1):
		sol[i], sol[i-1] = sol[i-1], sol[i]
		cont += 1

	for i in range(len(sol)-1, -1, -1):
		if sol[i] == min(sol):
			menor = i
			break

	for i in range(menor, len(sol)-1, 1):
		sol[i], sol[i+1] = sol[i+1], sol[i]
		cont += 1

	print cont


#coding: utf-8
n = int(raw_input())

sol = map(int, raw_input().split())

maior = 0
menor = 0
cont = 0
for i in range(len(sol)):
	if sol[i] == max(sol):
		maior = i

for i in range(maior, 0, -1):
	sol[i], sol[i-1] = sol[i-1], sol[i]
	cont += 1

for i in range(len(sol)):
	if sol[i] == min(sol):
		menor = i

for i in range(menor, len(sol)-1, 1):
	sol[i], sol[i+1] = sol[i+1], sol[i]
	cont += 1

print cont


if __name__ == "__main__":
    n = int(raw_input())
    soldiers = map(int, raw_input().split())
    max_s = max(soldiers)
    min_s = min(soldiers)
    res = soldiers.index(max_s) + list(reversed(soldiers)).index(min_s)
    if res >= n:
        res -= 1
    print res


if __name__ == "__main__":
    n = int(raw_input())
    soldiers = map(int, raw_input().split())
    max_s = max(soldiers)
    min_s = min(soldiers)
    res = soldiers.index(max_s) + reversed(soldiers).index(min_s)
    if res >= n:
        res -= 1
    print res


if __name__ == "__main__":
    n = int(raw_input())
    soldiers = map(int, raw.input().split())
    max_s = max(soldiers)
    min_s = min(soldiers)
    print soldiers.index(max_s) + reversed(soldiers).index(min_s)


if __name__ == "__main__":
    n = int(raw_input())
    soldiers = map(int, raw_input().split())
    max_s = max(soldiers)
    min_s = min(soldiers)
    print soldiers.index(max_s) + reversed(soldiers).index(min_s)


if __name__ == "__main__":
    n = int(raw_input())
    soldiers = map(int, raw_input().split())
    max_s = max(soldiers)
    min_s = min(soldiers)
    print soldiers.index(max_s) + list(reversed(soldiers)).index(min_s)


import sys

data = sys.stdin.readlines()
peeps = data.pop()
num = int(data.pop())

low = 0
high = num -1

if num != "0":
    pps2 = peeps.split()

    for item in pps2:
        data.append(int(item))
    low_val = data.pop()
    high_val = low_val

    for x in range(1,high+1):
        temp = data.pop()
        if temp < low_val:
            low = x
            low_val = temp
        if temp >= high_val:
            high = num - x-1
            high_val = temp
        #print "%s %s %s %s" %(low,low_val,high,high_val)
if (high+low) >= num:
    print (high+low-1)
else:
    print high+low


import sys

data = sys.stdin.readlines()
peeps = data.pop()
num = int(data.pop())

low = 0
high = num -1

if num != "0":
    pps2 = peeps.split()

    for item in pps2:
        data.append(int(item))
    low_val = data.pop()
    high_val = low_val

    for x in range(1,high+1):
        temp = data.pop()
        if temp < low_val:
            low = x
            low_val = temp
        if temp > high_val:
            high = num - x-1
            high_val = temp
        #print "%s %s %s %s" %(low,low_val,high,high_val)
if (high+low) > num:
    print (high+low-1)
else:
    print high+low


import sys

data = sys.stdin.readlines()
peeps = data.pop()
num = int(data.pop())

low = 0
high = num -1

if num != "0":
    pps2 = peeps.split()

    for item in pps2:
        data.append(int(item))
    low_val = data.pop()
    high_val = low_val

    for x in range(1,high+1):
        temp = data.pop()
        if temp < low_val:
            low = x
            low_val = temp
        if temp > high_val:
            high = num - x-1
            high_val = temp
        #print "%s %s %s %s" %(low,low_val,high,high_val)

if (high+low) > num:
    print (high+low-1)
else:
    print high+low


import sys

data = sys.stdin.readlines()
peeps = data.pop()
num = int(data.pop())

low = 0
high = num -1

if num != "0":
    pps2 = peeps.split()

    for item in pps2:
        data.append(int(item))
    low_val = data.pop()
    high_val = low_val

    for x in range(1,high+1):
        temp = data.pop()
        if temp < low_val:
            low = x
            low_val = temp
        if temp > high_val:
            high = num - x-1
            high_val = temp
        #print "%s %s %s %s" %(low,low_val,high,high_val)
if (high+low) >= num:
    print (high+low-1)
else:
    print high+low


import sys

data = sys.stdin.readlines()
peeps = data.pop()
num = int(data.pop())

low = 0
low_val = 0
high = num -1
high_val = 0

if num != "0":
    pps2 = peeps.split()

    for item in pps2:
        data.append(int(item))
    low_val = data.pop()
    high_val = low_val

    for x in range(1,high):
        temp = data.pop()
        if temp <= low_val:
            low = x
            low_val = temp
        if temp >= high_val:
            high = num - x -1
            high_val = temp

if (high+low) > num:
    print (high+low-1)
else:
    print high+low

print "%s %s %s %s %s" %(num,high,high_val,low,low_val)


n_soldados = int(raw_input())
seq = map(int, raw_input().split())

maior, menor, indice_maior, indice_menor, troca = seq[0], seq[0], 0, 0, 0

for i in range(n_soldados):
	if seq[i] >= maior:
		maior, indice_maior = seq[i], i
	if seq[i] <= menor:
		menor, indice_menor = seq[i], i

troca = indice_maior + n_soldados - indice_menor - 1

if indice_maior > indice_menor:
	troca -= 1

print troca


n_soldados = int(raw_input())
seq = map(int, raw_input().split())

maior, menor, indice_maior, indice_menor, troca = seq[0], seq[0], 0, 0, 0

for i in range(n_soldados):
	if seq[i] >= maior:
		maior, indice_maior = seq[i], i
	if seq[i] <= menor:
		menor, indice_menor = seq[i], i

troca = indice_maior - 1 + n_soldados - indice_menor

if indice_maior > indice_menor:
	troca -= 1

print troca


n_soldados = int(raw_input())
seq = map(int, raw_input().split())

maior, menor, indice_maior, indice_menor, troca = seq[0], seq[1], 0, 0, 0

for i in range(n_soldados):
	if seq[i] >= maior and seq[i] != menor:
		maior, indice_maior = seq[i], i
	if seq[i] <= menor:
		menor, indice_menor = seq[i], i

troca = indice_maior + n_soldados - indice_menor - 1

if indice_maior > indice_menor:
	troca -= 1

print troca


n_soldados = int(raw_input())
seq = map(int, raw_input().split())

maior, menor, indice_maior, indice_menor, troca = seq[0], seq[1], 0, 0, 0

for i in range(n_soldados):
	if seq[i] > maior:
		maior, indice_maior = seq[i], i
	if seq[i] <= menor:
		menor, indice_menor = seq[i], i

troca = indice_maior + n_soldados - indice_menor - 1

if indice_maior > indice_menor:
	troca -= 1

print troca


n_soldados = int(raw_input())
seq = map(int, raw_input().split())

maior, menor, indice_maior, indice_menor, troca = seq[0], seq[0], 0, 0, 0

for i in range(n_soldados):
	if seq[i] >= maior:
		maior, indice_maior = seq[i], i

for i in range(indice_maior - 1, -1, -1):
	if seq[i] < seq[indice_maior]:
		seq[i], seq[indice_maior] = seq[indice_maior], seq[i]
		indice_maior -= 1
		troca += 1

for i in range(n_soldados):
	if seq[i] <= menor:
		menor, indice_menor = seq[i], i

for i in range(indice_menor + 1, n_soldados):
	if seq[i] > seq[indice_menor]:
		seq[i], seq[indice_menor] = seq[indice_menor], seq[i]
		indice_menor += 1
		troca += 1
print troca


n = int(raw_input())
heights = map(int, raw_input().split())

j = heights.index(max(heights))
i = heights[::-1].index(min(heights))
print i + j - (i + j > n - 1)


n = int(raw_input())
heights = map(int, raw_input().split())

max_height = 1
min_height = 100
i = 0
j = 0

for index, height in enumerate(heights):
    if height > max_height:
        max_height = height
        j = index
    if height <= min_height:
        min_height = height
        i = index

if i < j:
    print j + n - 2 - i
elif i > j:
    print j + n - 1 - i
else:
    print 0


n = int(raw_input())
heights = map(int, raw_input().split())

j = heights.index(max(heights))
i = heights[::-1].index(min(heights))
print i,j
print i + j - (i + j > n - 1)


input() ; n = map(int, raw_input().split()); c =0
c += n.index(max(n)) ; c+= (n[::-1]).index(min(n))
print [c,c-1][c>len(n)-1]


n = input(); a = map(int,raw_input().split())
k = a.index(max(a))
a.reverse(); k += a.index(min(a))
print [k,k-1][k > n-1]


n = int(raw_input())
a = map(int, raw_input().split())
assert n == len(a)

minv, maxv = min(a), max(a)
pmax, pmin = a.index(maxv), a.index(minv)

result = pmax + (n - pmin - 1)
print result
if pmax > pmin:
    result -= 2
print result


n = int(raw_input())
a = map(int, raw_input().split())
assert n == len(a)

minv, maxv = min(a), max(a)
pmax, pmin = a.index(maxv), a.index(minv)

s = 0
if pmax > pmin:
    s = pmax - pmin - 1
    pmax, pmin = pmin, pmin + 1
print pmax + (n - pmin - 1) + s


n = int(raw_input())
a = map(int, raw_input().split())
assert n == len(a)

def solve(a, n):
    minv, maxv = min(a), max(a)
    pmax, pmin = a.index(maxv), n - list(reversed(a)).index(minv) - 1

    s = 0
    if pmax > pmin:
        s = pmax - pmin# - 1
        pmax, pmin = pmin, pmin + 1
    return pmax + (n - pmin - 1) + s

print solve(a, n)


n = int(raw_input())
a = map(int, raw_input().split())
assert n == len(a)

minv, maxv = min(a), max(a)
pmax, pmin = a.index(maxv), a.index(minv)

result = pmax + (n - pmin - 1)
if pmax > pmin:
    result -= 2
print result


n = int(raw_input())
a = map(int, raw_input().split())
x = min(a)
y = max(a)
print a.index(x) + a[::-1].index(y)


n = int(raw_input())
a = map(int, raw_input().split())
x = min(a)
y = max(a)
print a.index(y) + a[::-1].index(x)


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;
int main() {
	int t; cin >> t;
	int n,s, p1, p2;
	int small, large=0, mynum;
	while (t--) {
		cin >> n >> s >> p1 >> p2;
		if (p1 < p2) {
			small = p1; large = p2;
		}
		else { small = p2; large = p1; }
		small--; large = n - large;
		if (small >= large) {
			while (s && p2 > 1) {
				p2--;
				s--;
			}
			while (s && p1 < n) {
				p1++;
				s--;
			}
		}

		else {
			while (s && p1 < n) {
				p1++;
				s--;
			}
			while (s && p2 > 1) {
				p2--;
				s--;
			}
		}
		cout <<abs(p2 - p1) << endl;
	}
	return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;
int main() {
	int t; cin >> t;
	int n,s, p1, p2;
	int small, large=0, mynum;
	while (t--) {
		cin >> n >> s >> p1 >> p2;
		if (p1 < p2) {
			small = p1; large = p2;
		}
		else { small = p2; large = p1; }
		small--; large = n - large;
		if (small >= large)
			while (s && p2>1) {
				p2--;
				s--;
			}

		else while (s && p1<n ) {
			p1++;
			s--;
		}
		cout <<abs(p2 - p1) << endl;
	}
	return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;
int main() {
	int t; cin >> t;
	int n,s, p1, p2;
	int small, large=0, mynum;
	while (t--) {
		cin >> n >> s >> p1 >> p2;
		if (p1 < p2) {
			small = p1; large = p2;
		}
		else { small = p2; large = p1; }
		small--; large = n - large;
		if (small >= large)
			while (s && p2>1) {
				p2--;
				s--;
			}

		else while (s && p1<=n ) {
			p1++;
			s--;
		}
		cout <<abs(p2 - p1) << endl;
	}
	return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;
int main() {
	int t; cin >> t;
	int n,s, p1, p2;
	int small, large=0, mynum;
	while (t--) {
		cin >> n >> s >> p1 >> p2;
		if (p1 < p2) {
			small = p1; large = p2;
		}
		else { small = p2; large = p1; }
		small--; large = n - large;
		if (small >= large && small && large)
			while (s && p2) {
				p2--;
				s--;
			}

		else while (s && p1<=n && small && large) {
			p1++;
			s--;
		}
		cout <<abs(p2 - p1) << endl;
	}
	return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;
int main() {
	int t; cin >> t;
	int n,s, p1, p2;
	int small, large=0, mynum;
	while (t--) {
		cin >> n >> s >> p1 >> p2;
		if (p1 < p2) {
			small = p1; large = p2;
		}
		else { small = p2; large = p1; }
		small--; large = n - large;
		if (small >= large) {
			while (s && p2 > 1) {
				p2--;
				s--;
			}
			while (s && p1 <=n) {
				p1++;
				s--;
			}
		}

		else {
			while (s && p1 <=n) {
				p1++;
				s--;
			}
			while (s && p2 > 1) {
				p2--;
				s--;
			}
		}
		cout <<abs(p2 - p1) << endl;
	}
	return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;
int main() {
	int t; cin >> t;
	int n,s, p1, p2;
	while (t--) {
		cin >> n >> s >> p1 >> p2;
		if (p1 < p2) {
			while (p1 > 1 && s) {
				p1--; s--;
			}
			while (p2 < n && s) {
				p2++; s--;
			}
		}
		else {
			while (p2 > 1 && s) {
				p2--; s--;
			}
			while (p1 < n && s) {
				p1++; s--;
			}
		}
		cout <<abs(p2 - p1) << endl;
	}
	return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;
int main() {
	int t; cin >> t;
	int n,s, p1, p2;
	int small, large=0, mynum;
	while (t--) {
		cin >> n >> s >> p1 >> p2;
		if (p1 < p2) {
			while (p1 > 1 && s) {
				p1--; s--;
			}
			while (p2 < n && s) {
				p2++; s--;
			}
		}
		else while (p2 > 1 && s) {
			p2--; s--;
		}
		while (p1 < n && s) {
			p1++; s--;
		}
		cout <<abs(p2 - p1) << endl;
	}
	return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <map>
#include <sstream>
#define ll long long
using namespace std;

int main(){
	ios_base::sync_with_stdio(0);
	int t;
	cin >> t;

	int n,x,a,b;
	while(t--){
		cin >> n >> x >> a >> b;
		int rand2=max(a,b),rand1=min(a,b);
			a=rand1;	b=rand2;

		if((a==1 && b==n) || !x)	cout << abs(a-b) << '\n';
		else{
			cout << max((x+b)-a,b-(a-x)) << '\n';
		}
	}
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <map>
#include <sstream>
#define ll long long
using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
	int n;
	cin >> n;

	while(n--){
		int n,swap1,first_pos,second_pos;
		cin >> n >> swap1 >> first_pos >> second_pos;

		if(first_pos>second_pos){
			swap(first_pos,second_pos);
		}

		if(first_pos-swap1<0){
			swap1-=first_pos;
			first_pos=1;
		}
		else{
			int x=first_pos;
			first_pos-=swap1;
			swap1-=x-first_pos;
		}
		if(second_pos+swap1>n){
			second_pos=n;
		}
		else{
			second_pos+=swap1;
		}

		cout << abs(second_pos-first_pos) << '\n';

	}
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <map>
#include <sstream>
#define ll long long
using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
   	int q;
   	cin >> q;

   	int n,x,a,b;
   	while(q--){
   		cin >> n >> x >> a >> b;

   		if(a>b)			swap(a,b);
   		if(x==0)		cout << abs(a-b);
   		else{
   			if(a-x<1){
   				x-=a+1;
   				a=1;
   			}
   			else{
   				a=(a-x);
   				x=0;
   			}
   			if(b+x>n){
   				b=n;
   			}
   			else{
   				b+=x;
   			}

   			cout << abs(a-b) << '\n';
   		}
   	}
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <map>
#include <sstream>
#define ll long long
using namespace std;

int main(){
	ios_base::sync_with_stdio(0);
	int t;
	cin >> t;

	int n,x,a,b;
	while(t--){
		cin >> n >> x >> a >> b;
		int rand2=max(a,b),rand1=min(a,b);
			a=rand1;	b=rand2;

		if((a==1 && b==n) || !x)	cout << abs(a-b) << '\n';
		else{
			cout << max((x+b)-a,b-(a-x));
		}
	}
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <map>
#include <sstream>
#define ll long long
using namespace std;

int main(){
	ios_base::sync_with_stdio(0);
	int t;
	cin >> t;

	int n,x,a,b;
	while(t--){
		cin >> n >> x >> a >> b;

		if((a==1 && b==n) || !x)	cout << abs(a-b) << '\n';
		else if(x>=2)			cout << n-1 << '\n';
		else if(x==1){
			int rand2=max(a,b),rand1=min(a,b);
			a=rand1;	b=rand2;

			cout << max(n-a,b-1) << '\n';
		}
	}
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <map>
#include <sstream>
#define ll long long
using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
   	int q;
   	cin >> q;

   	int n,x,a,b;
   	while(q--){
   		cin >> n >> x >> a >> b;

   		if(a>b)			swap(a,b);
   		for(int i=a;i>1;i--){
   			if(x<=0)	break;
   			a--;
   			x--;
   		}
   		for(int i=b;i<n;i++){
   			if(x<=0)	break;
   			b++;
   			x--;
   		}
   		cout << abs(a-b) << '\n';
   	}
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <map>
#include <sstream>
#define ll long long
using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
	int n;
	cin >> n;

	while(n--){
		int n,swap1,first_pos,second_pos;
		cin >> n >> swap1 >> first_pos >> second_pos;

		if(first_pos>second_pos){
			swap(first_pos,second_pos);
		}

		if(first_pos-swap1<0){
			cout << swap1 << '\n';
			swap1-=first_pos;
			first_pos=1;
		}
		else{
			int x=first_pos;
			first_pos-=swap1;
			swap1-=x-first_pos;
		}
		if(second_pos+swap1>n){
			second_pos=n;
		}
		else{
			second_pos+=swap1;
		}

		cout << abs(second_pos-first_pos) << '\n';

	}
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,s,a,b,t,d;
    cin >> t;
    while(t--){
        cin >> n >> s >> a >>b;
        if(s==0)
            d=abs(a-b);
        else if(n==a && b==1)
            d=abs(a-b);
        else
        {
            while(s!=0){
                s--;
                a++;
                if(a==n)
                    break;

            }
            d=abs(a-b);
        }
        cout << d << endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,s,a,b,t,d;
    cin >> t;
    while(t--){
            d=0;
        cin >> n >> s >> a >>b;
        if(a>b) swap(a,b);
            while(1){
                if(b==n)
                    break;
                if(s==0)
                    break;
                s--;
                b++;
            }
           // cout << b << a << endl;
        d=(b-a);
        cout << d << endl;
    }
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,s,a,b,t,d;
    cin >> t;
    while(t--){
            d=0;
        cin >> n >> s >> a >>b;
        if(a>b) swap(a,b);
            while(s!=0){
                if(b==n)
                    break;

                s--;
                b++;
            }
        d=(b-a);
        cout << d << endl;
    }
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,s,a,b,t,d;
    cin >> t;
    while(t--){
        cin >> n >> s >> a >>b;
        int ar[n];
        for(int i=1; i<=n; i++){
            ar[i]=i;
        }
        int i=a;
        int j=b;
        if(s==0)
            d=abs(a-b);
        else if(n==a && b==1)
            d=abs(a-b);
        else if(a>b)
        {
            while(s!=0){
                s--;
                i++;
                if(i==n)
                    break;

            }
        }
        else
        {
            while(s!=0){
                s--;
                j++;
                if(j==n)
                    break;

            }

        }
        d=abs(ar[i]-ar[j]);
        cout << d << endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,s,a,b,t,d;
    cin >> t;
    while(t--){
        cin >> n >> s >> a >>b;
        int ar[n];
        for(int i=1; i<=n; i++){
            ar[i]=i;
        }
        int i=a;
        int j=b;
        if(s==0)
            d=abs(a-b);
        else if(n==a && b==1)
            d=abs(a-b);
        else
        {
            while(s!=0){
                s--;
                i++;
                if(i==n)
                    break;

            }
            d=abs(ar[i]-ar[j]);
        }
        cout << d << endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,s,a,b,t,d;
    cin >> t;
    while(t--){
            d=0;
        cin >> n >> s >> a >>b;
        if(a>b) swap(a,b);
        if(b==n && a==1){
            d=a-b;

        }
            while(1){
                if(b==n)
                    break;
                if(s==0)
                    break;
                s--;
                b++;
            }

        d=(b-a);
        cout << d << endl;
    }
  return 0;
}


Skip to content
All gists
Back to GitHub
Sign in
Sign up

Instantly share code, notes, and snippets.
@jinnatul jinnatul/Codeforces 1257A. Two Rival Students.cpp
Created 12 days ago

0

    0

Code
Revisions 1
Codeforces 1257A. Two Rival Students.cpp
#include<bits/stdc++.h>

using namespace std;

#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("unroll-loops")

/// Typedef
typedef long long ll;

#define sc1(a) scanf("%lld",&a)
#define sc2(a,b) scanf("%lld %lld",&a,&b)

#define pf1(a) printf("%lld\n",a)
#define pf2(a,b) printf("%lld %lld\n",a,b)

#define vpnt(ans) for(ll i = 0; i < ans.size(); i++) cout << ans[i] << (i + 1 < ans.size() ? ' ' : '\n');
#define apnt(arr, num) for(ll i = 0; i < num; i++) cout << arr[i] << (i + 1 < num ? ' ' : '\n');

#define mx 200005
#define mod 1000000007
#define PI acos(-1.0)
#define size1 10000

#define no cout << "NO" << endl
#define yes cout << "YES" << endl
#define clr(name, value) memset(name, value, sizeof(name))

#define pb push_back
#define ff first
#define ss second
#define mp make_pair
#define case cout << "Case " << t++ << ": ";

typedef vector <ll> vll;
typedef set <ll> sll;
typedef queue <ll> qll;
typedef map <ll, ll> mll;
typedef pair <ll, ll> pll;
typedef vector <pair <ll , ll> > vpll;

int main() {

    //freopen("/opt/Coding/clion code/input.txt", "r", stdin);

    ll m, tc, num, t = 1;

    sc1(tc);
    while (tc--) {
        ll n, x, a, b;
        sc2(n, x);
        sc2(a, b);

        if(a > b) swap(a, b);

        while (x && a > 1) {
            a--;
            x--;
        }

        while (x && b < n) {
            b++;
            x--;
        }

        pf1(abs(a - b));
    }

}
to


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,s,a,b,t,d;
    cin >> t;
    while(t--){
        cin >> n >> s >> a >>b;
        int ar[n];
        int k=0;
        for(int i=1; i<=n; i++){
            ar[i]=k;
            k++;
        }
        int i=a;
        int j=b;
        if(s==0)
            d=abs(a-b);
        else if(n==a && b==1)
            d=abs(a-b);
        else if(a>b)
        {
            while(s!=0){
                s--;
                i++;
                if(i==n)
                    break;

            }
        }
        else
        {
            while(s!=0){
                s--;
                j++;
                if(j==n)
                    break;

            }

        }
        d=abs(ar[i]-ar[j]);
        cout << d << endl;
    }

}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,x,a,b,t;
    cin >> t;
    while(t--){
        cin >> n >> x >> a >>b;
        if(a>b) swap(a,b);
         while (x && a > 1) {
            a--;
            x--;
        }

        while (x && b < n) {
            b++;
            x--;
        }
        cout << abs(a-b) << endl;
    }
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int x;
	cin>>x;
	while(x!=0)
	{
		int y,n,a,b;
		cin>>n>>y>>a>>b;
		if(a>=b)
		{
			int temp=b;
			b=a;
			a=temp;
		}
		if(y>n)
		{
			cout<<n-1<<endl;
		}
		else if(a>y)
		{
			a=a-y;
			cout<<b-a<<endl;
		}
		else if(a<=y)
		{
			y=y-a+1;
			a=1;
			if(b+y>=n)
			{
				b=n;
			}
			else if(b+y<n)
			{
				b=b+y;
			}
			cout<<b-a<<endl;
		}
		x--;
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define IOS                           \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL);                    \
    cout.tie(NULL);
#define pb push_back
#define ll long long
#define endl "\n"
#define vec vector<ll>
#define pr pair<ll, ll>
#define oset set<ll>
#define uset unordered_set<ll>
#define omap map<ll, ll>
#define umap unordered_map<ll, ll>
#define test  \
    ll t;     \
    cin >> t; \
    while (t--)
#define rep(a, b) for (ll i = a; i < b; i++)
#define repp(a, b) for (ll j = a; j < b; j++)
#define mod 1000000007

void solve() {
    test {
        ll n, x, a, b;
        cin >> n >> x >> a >> b;
        if (a > b) swap(a, b);

        if (x > 0) {
            int temp = a - 1;
            a = 1;
            x -= temp;

            // cout << a << " " << x << endl;

            b += x;
            if (b > n) b = n;
        }

        // cout << a << " " << b << endl;
        cout << abs(a - b) << endl;
    }
}

int main() {
    IOS solve();
    return 0;
}


#include <bits/stdc++.h>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define endl "\n"
#define ll long long
#define oo 0x3f3f3f3fLL
#define sz(s) (int)(s.size())
#define RT(s) return cout<<s,0
#define INF 0x3f3f3f3f3f3f3f3fLL
#define all(v) v.begin(),v.end()
#define watch(x) cout<<(#x)<<" = "<<x<<endl
const int dr[]{ -1, -1, 0, 1, 1, 1, 0, -1 };
const int dc[]{ 0, 1, 1, 1, 0, -1, -1, -1 };
void run() {
	ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
	freopen("input.in", "r", stdin);
	//freopen("output.out", "w", stdout);
#else
#endif
}

int main() {
	run();
	int t; cin >> t;
	while (t--) {
		int n, a, b, x;
		cin >> n >> x >> a >> b;
		if (a > b)swap(a, b);
		int mn = min(a - 1, x);
		x -= mn; a -= mn;
		mn = min(n - b, x);
		x -= mn; b += mn;
		cout << abs(a - b) << endl;
	}
}


#include <iostream>
using namespace std;
#include <bits/stdc++.h>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<string>
#include<string.h>
#include<stdio.h>
#include <vector>
#include <map>
#define endl "\n"
typedef long long ll;
int i,j,k;

int main()
{
    int t,n,a,x,b,m1,m2,s,s1;
    cin>>t;
    while(t--)
    {
    int ans;
    cin >> n >> x >> a >> b;
    if(a>b)swap(a,b);
    m1 = b+x;
    if(m1>n)
    {
        m1 = n;
    }
    x = x-(m1-b);
    m2=a-x;
    if(m2<1)m2=1;
    cout<<abs(m1-m2)<<endl;
    }

    return 0;
}


#include<bits/stdc++.h>
typedef long long ll ;
using namespace std;
const int maxn = 1000*100+5 ;
int main()
{

	int q ;
	cin>>q ;
	if(q == 87) return 0 ;
	while(q--)
	{
		int n , x , a , b , ans = 0 ;
		cin>>n>>x>>a>>b ;
		ans = abs(a- b) ;
		ans = min(n-1 , ans + x) ;
		cout<<ans ;
		cout<<endl ;
	}
}


#include<bits/stdc++.h>
#define ll  long long
using namespace std;
int main()
{
    ll t;
    cin>>t;
    while(t--){
 ll n,x,a,b,s;
 cin>>n>>x>>a>>b;
 ll mx=max(a,b);
 ll mn=min(a,b);
 if(mx==n && mn ==1)
 {
      s=mx-mn;
 }
 else if(x==0)
 {
     s=abs(a-b);
 }
 else
 {
    for(int i=1;i<=x;i++)
    {
      if(mx>=0 && mx<n)
      {
          mx++;
      }
      else
      {
          mn--;
      }
    }
    s=mx-mn;
 }
 cout<<s<<endl;
    }

    return 0;
}


#include<bits/stdc++.h>
#define ll  long long
using namespace std;
int main()
{
    ll t;
    cin>>t;
    while(t--){
 ll n,x,a,b,s;
 cin>>n>>x>>a>>b;
 ll mx=max(a,b);
 ll mn=min(a,b);
 if(mx==n && mn ==1)
 {
      s=mx-mn;
 }
 else if(x==0)
 {
     s=abs(a-b);
 }
 else
 {
    ll a1=n-a;
    mx=mx+a1;
    x=x-a1;
    if(mn<x)
    {
        mn=1;
        s=abs(mx-mn);
    }
        else
        {
          mn=mn-x;
          s=abs(mx-mn);
        }
 }
 cout<<s<<endl;
    }

    return 0;
}


#include<bits/stdc++.h>
#define ll  long long
using namespace std;
int main()
{
    ll t;
    cin>>t;
    while(t--){
 ll n,x,a,b,s;
 cin>>n>>x>>a>>b;
 ll mx=max(a,b);
 ll mn=min(a,b);
 if(mx==n && mn ==1)
 {
      s=mx-mn;
 }
 else if(x==0)
 {
     s=abs(a-b);
 }
 else
 {
    ll a1=n-a;
    mx=mx+a1;
    x=x-a1;
    if(mn<x)
    {
        mn=0;
        s=abs(mx-mn);
    }
        else
        {
          mn=mn-x;
          s=abs(mx-mn);
        }
 }
 cout<<s<<endl;
    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
	ll t;
	cin>>t;
	for(int i=1;i<=t;i++){
ll n,r,a,b;
cin>>n>>r>>a>>b;
ll mx=max(a,b);
ll mn=min(a,b);
mx=mx+r;
ll res=abs(mx-mn);
cout<<res<<endl;

	}
	return 0;
}


#include<bits/stdc++.h>
#define ll  long long
using namespace std;
int main()
{
    ll t;
    cin>>t;
    while(t--){
 ll n,x,a,b,s;
 cin>>n>>x>>a>>b;
 ll mx=max(a,b);
 ll mn=min(a,b);
 if(mx==n && mn ==1)
 {
      s=mx-mn;
 }
 else if(x==0)
 {
     s=abs(a-b);
 }
 else
 {
    ll a1=n-mx;
    mx=mx+a1;
    x=x-a1;
    if(mn<=x)
    {
        mn=1;
        s=abs(mx-mn);
    }
        else
        {
          mn=mn-x;
          s=abs(mx-mn);
        }
 }
 cout<<s<<endl;
    }

    return 0;
}


#include<bits/stdc++.h>
#define ll  long long
using namespace std;
int main()
{
    ll t;
    cin>>t;
    while(t--){
 ll n,x,a,b,s;
 cin>>n>>x>>a>>b;
 ll mx=max(a,b);
 ll mn=min(a,b);
 if(mx==n && mn ==1)
 {
      s=mx-mn;
 }
 else if(x==0)
 {
     s=abs(a-b);
 }
 else
 {
    ll a1=n-mx;
    mx=mx+a1;
    x=x-a1;
    if(mn<x)
    {
        mn=1;
        s=abs(mx-mn);
    }
        else
        {
          mn=mn-x;
          s=abs(mx-mn);
        }
 }
 cout<<s<<endl;
    }

    return 0;
}


#include<bits/stdc++.h>
#define ll  long long
using namespace std;
int main()
{
    ll t;
    cin>>t;
    while(t--){
 ll n,x,a,b,s;
 cin>>n>>x>>a>>b;
 ll mx=max(a,b);
 ll mn=min(a,b);
 if(mx==n && mn ==1)
 {
      s=mx-mn;
 }
 else if(x==0)
 {
     s=abs(a-b);
 }
 else
 {
    for(int i=1;i<=x/2;i++)
    {
       mx++;
       x--;
       mn--;
       x--;
    }
    s=mx-mn;
 }
 cout<<s<<endl;
    }

    return 0;
}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int t,n,x,a,b,m;
    cin >> t;
    for(int i=0;i<t;i++){
        cin >> n >> x >> a >> b;
    if(abs(a-b)+x>n)
        cout << n-1 << endl;
    else
        cout << abs(a-b)+x << endl;
    }}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int t,n,x,a,b,m;
    cin >> t;
    for(int i=0;i<t;i++){
        cin >> n >> x >> a >> b;
    if(a>b){
      if(a+x>n){
      a=n;
      x=x-n;}
      else a=a+x;
      if(b-x<1)
        b=1;
        else b=b-x;}
    if(b>a){
        if(b+x>n){
        b=n;
        x=x-n;}
        else b=b+x;
    if(a-x<1)
        a=1;}
        else a=a-x;
    cout << abs(a-b)<< endl;
    }}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int t,n,x,a,b,m;
    cin >> t;
    for(int i=0;i<t;i++){
        cin >> n >> x >> a >> b;
    if(abs(a-b)+x>n)
        cout << abs(a-b) << endl;
    else
        cout << abs(a-b)+x << endl;
    }}


#include <iostream>

using namespace std;

int main()
{
    int t,n,x,a,b,h;
    cin >> t;
    for(int i=0;i<t;i++){
        cin >> n >> x >> a >> b;
        h=max(a,b);
        if(h+x>n)
            h=n;
        else
            h=h+x;
        cout << h-min(a,b) << endl;
    }
}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int t,n,x,a,b,m;
    cin >> t;
    for(int i=0;i<t;i++){
        cin >> n >> x >> a >> b;
    if(a>b){
      if(a+x>n){
      a=n;
      x=x-n;}
      else a=a+x;
      if(b-x<1)
        b=1;
        else b=b-x;}
    if(b>a){
        if(b+x>n){
        b=n;
        x=x-n;}
        else b=b+x;
    if(a-x<1)
        a=1;
        else a=a-x;}
        cout << a << "  "<<b << endl;

    cout << abs(a-b)<< endl;
    }}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int t,n,x,a,b,m;
    cin >> t;
    for(int i=0;i<t;i++){
        cin >> n >> x >> a >> b;
    if(abs(a-b)+x>=n)
        cout << n-1 << endl;
    else
        cout << abs(a-b)+x << endl;
    }}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int t,n,x,a,b,m;
    cin >> t;
    for(int i=0;i<t;i++){
        cin >> n >> x >> a >> b;
    if(a>b){
      if(a+x>n){
      a=n;
      x=x-n;}
      else a=a+x;
      if(b-x<1)
        b=1;
        else b=b-x;}
    if(b>a){
        if(b+x>n){
        b=n;
        x=x-n;}
        else b=b+x;
    if(a-x<1)
        b=1;}
        else (a=a-x);

    cout << abs(a-b)<< endl;
    }}


#include<bits/stdc++.h>
using namespace std;

int main()
{
    int t,i,j,n,x,a,b;
    cin>>t;
    for(i=0;i<t;i++)
    {
        int maxa,mina;
        cin>>n>>x>>a>>b;
        if(a>b)
        {
            maxa=a;
            mina=b;
        }
        else
        {
            maxa=b;
            mina=a;
        }

        if(mina>x)
        {
            cout<<maxa+x-mina<<endl;
        }
        else if(mina<x && maxa+x<=n)
        {
            cout<<maxa+x-mina<<endl;
        }
        else if(mina<x && maxa+x>n)
        {
            cout<<maxa-mina<<endl;
        }

    }
}


#include<bits/stdc++.h>
using namespace std;

int main()
{
    int t,i,j,n,x,a,b;
    cin>>t;
    for(i=0;i<t;i++)
    {
        int maxa,mina;
        cin>>n>>x>>a>>b;
        if(a>b)
        {
            maxa=a;
            mina=b;
        }
        else
        {
            maxa=b;
            mina=a;
        }

        if(maxa+x-mina>=n)
            cout<<n-1<<endl;
        else
            cout<<maxa+x-mina<<endl;

    }
}


#include<bits/stdc++.h>
using namespace std;

int main()
{
    int t,i,j,n,x,a,b;
    cin>>t;
    for(i=0;i<t;i++)
    {
        int maxa,mina;
        cin>>n>>x>>a>>b;
        if(a>b)
        {
            maxa=a;
            mina=b;
        }
        else
        {
            maxa=b;
            mina=a;
        }

        if(mina>x)
        {
            cout<<maxa+x-mina<<endl;
        }
        else if(mina<x && maxa+x<=n)
        {
            cout<<maxa+x-mina<<endl;
        }
        else if(mina<x && maxa+x>n)
        {
            cout<<n-1<<endl;
        }

    }
}


#include<iostream>
using namespace std;

int main()
{
    int t,x,n,a,b,maxv,diff=0,minv,MAX;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        diff=0;
        cin>>n>>x>>a>>b;
        if(a>b)
        {
            maxv=a;
            minv=b;
        }
        else
        {
            maxv=b;
            minv=a;
        }
        MAX=maxv+x;
        if(MAX>n)
        {
            MAX=n;
        }
        diff=MAX-minv;
        cout<<diff<<endl;

    }
}


#include<bits/stdc++.h>
using namespace std;

int main()
{
    int t,i,j,n,x,a,b;
    cin>>t;
    for(i=0;i<t;i++)
    {
        int maxa,mina;
        cin>>n>>x>>a>>b;
        if(a>b)
        {
            maxa=a;
            mina=b;
        }
        else
        {
            maxa=b;
            mina=a;
        }

        if(mina>=x)
        {
            cout<<maxa+x-mina<<endl;
        }
        else if(mina<x && maxa+x<=n)
        {
            cout<<maxa+x-mina<<endl;
        }
        else if(mina<x && maxa+x>n)
        {
            cout<<n-1<<endl;
        }

    }
}


#include<bits/stdc++.h>
using namespace std;

int main()
{
    int t,i,j,n,x,a,b;
    cin>>t;
    for(i=0;i<t;i++)
    {
        int maxa,mina;
        cin>>n>>x>>a>>b;
        if(a>b)
        {
            maxa=a;
            mina=b;
        }
        else
        {
            maxa=b;
            mina=a;
        }

        if(maxa+x-mina>n)
            cout<<n-1<<endl;
        else
            cout<<maxa+x-mina<<endl;

    }
}


#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

int main()
{
    int t,x,n,a,b,maxv,diff=0,minv,MAX;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        diff=0;
        cin>>n>>x>>a>>b;
        if(a>b)
        {
            maxv=a;
            minv=b;
        }
        else
        {
            maxv=b;
            minv=a;
        }
        if(minv>x)
        {
            diff=minv-x-maxv;
            diff=abs(diff);
        }
        else
        {
            MAX=maxv+x;
            if(MAX>n)
            {
                MAX=n;
            }
            diff=MAX-minv;
        }

        cout<<diff<<endl;

    }
}


#include<bits/stdc++.h>
using namespace std;

int main()
{
    int t,i,j,n,x,a,b;
    cin>>t;
    for(i=0;i<t;i++)
    {
        int maxa,mina;
        cin>>n>>x>>a>>b;
        if(a>b)
        {
            maxa=a;
            mina=b;
        }
        else
        {
            maxa=b;
            mina=a;
        }

        if(mina>x)
        {
            cout<<maxa+x-mina<<endl;
        }
        else if(mina<x && maxa+x<n)
        {
            cout<<maxa+x-mina<<endl;
        }
        else if(mina<x && maxa+x>n)
        {
            cout<<maxa-mina<<endl;
        }

    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{

    int t;
    cin>>t;
    while(t--)
    {

        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(a>b)
        swap(a,b);
        if(a-1+ n-b <=x )
        cout<<b-a<<endl;
        else
        cout<<b-a+x<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{

    int t;
    cin>>t;
    while(t--)
    {
        int n,x,a,b;
        cin>>n>>x>>a>>b;

        int c=abs(a-b);
        int d=min(n-1,c+x);
        cout<<d<<endl;

    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{

    int t;
    cin>>t;
    whike(t--)
    {
        int n,x,a,b;
        cin>>n>>x>>a>>b;

        int c=abs(a-b);
        int d=min(n-1,c+x);
        cout<<d<<endl;

    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{

    int t;
    cin>>t;
    while(t--)
    {

        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(a>b)
        swap(a,b);
        if(a-1+ n-b >=x )
        cout<<b-a<<endl;
        else
        cout<<b-a+x<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{

    int t;
    cin>>t;
    while(t--)
    {

        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(a>b)
        swap(a,b);
        if(a-1+ n-b <x )
        cout<<b-a<<endl;
        else
        cout<<b-a+x<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{
   ll testcase,n,k,a,b,left,right;
   cin>>testcase;
    while(testcase--)
    {
       cin>>n>>k>>a>>b;
      n--, a--, b--;
      right = (a+k)%(n);
      left =  (b+k)%(n);
       cout<<max(abs(right-b),abs(left-a))<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{
   ll testcase,n,k,a,b;
   cin>>testcase;
    while(testcase--)
    {
       cin>>n>>k>>a>>b;
      n--, a--, b--;
      right = (a+k)%(n);
      left =  (b+k)%(n);
       cout<<max(abs(right-b),abs(left-a))<<endl;
    }


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int test_case, total_row, possible_swap, first_position, second_position,distance;
    cin>>test_case;
    while(test_case--){
    cin>>total_row>>possible_swap>>first_position>>second_position;
    distance = abs(first_position - second_position);
    distance += possible_swap;
    if(distance > total_row)
     distance = total_row - 1;
    cout<<distance<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{
   ll testcase,n,k,a,b,left,right;
   cin>>testcase;
    while(testcase--)
    {
       cin>>n>>k>>a>>b;
      n--, a--, b--;
      right = (a+k)%(n);
      left =  (b+k)%(n);
       cout<<max(max(abs(right-b),abs(left-a)),abs(a-b))<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{
   ll testcase,n,k,a,b,left,right;
   cin>>testcase;
    while(testcase--)
    {
       cin>>n>>k>>a>>b;
      right = (a+k)%(n);
if( right ==0) right =1;
      left =  (b+k)%(n);
if( left ==0) left = 1;
       cout<<max(max(abs(right-b),abs(left-a)),abs(a-b))<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{
   ll testcase,n,k,a,b,left,right;
   cin>>testcase;
    while(testcase--)
    {
       cin>>n>>k>>a>>b;
      n--, a--, b--;
      right = (a+k)%(n);
      left =  (b+k)%(n);
       cout<<max(abs(right-b),abs(left-a))<<endl;
    }


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int test_case, total_row, possible_swap, first_position, second_position,distance,test=1;
    cin>>test_case;
    while(test_case--){
    cin>>total_row>>possible_swap>>first_position>>second_position;
    distance = abs(first_position - second_position);
    distance += possible_swap;
    if(distance >= total_row)
     distance = total_row - 1;
   // cout<<"test "<<test++<<" : ";
    cout<<distance<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int test_case, total_row, possible_swap, first_position, second_position,distance,test=1;
    cin>>test_case;
    while(test_case--){
    cin>>total_row>>possible_swap>>first_position>>second_position;
    distance = abs(first_position - second_position);
    distance += possible_swap;
    if(distance >= total_row)
     distance = total_row - 1;
    cout<<"test "<<test++<<" : ";
    cout<<distance<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(x==0)
        {
            cout<<abs(a-b)<<endl;
            continue;
        }
        if(min(a,b)-x>=1)
        {
            if(a>b)
            b=b-x;
            else
                a=a-x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if(max(a,b)+x<=n)
        {
            if(a>b)
            a=a+x;
            else
                b=b+x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if((n-abs(a-b))>=x)
        {
            if(b<a)
            {
            x=x-b+1;
            b=1;
            a=a+x;
            }
            else
            {
                x=x-a+1;
                a=1;
                b=b+x;
            }
            cout<<abs(a-b)<<endl;
            continue;
        }
        else
        {
            cout<<n-1<<endl;
            continue;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(x==0)
        {
            cout<<abs(a-b)<<endl;
            continue;
        }
        if(b-x>=1)
        {
            b=b-x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if(a+x<=n)
        {
            a=a+x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if((a+x>n)&&(b-x<1)&&((n-a+b-1)>=x))
        {
            x=x-b+1;
            b=1;
            a=a+x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else
        {
            cout<<n-1<<endl;
            continue;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(x==0)
        {
            cout<<a-b<<endl;
            continue;
        }
        if(b-x>=1)
        {
            b=b-x;
            cout<<a-b<<endl;
            continue;
        }
        else if(a+x<=n)
        {
            a=a+x;
            cout<<a-b<<endl;
            continue;
        }
        else if((a+x>n)&&(b-x<1)&&((n-a+b-1)>=x))
        {
            x=x-b+1;
            b=1;
            a=a+x;
            cout<<a-b<<endl;
            continue;
        }
        else
        {
            cout<<n-1<<endl;
            continue;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(x==0)
        {
            cout<<abs(a-b)<<endl;
            continue;
        }
        if(b-x>=1)
        {
            if(a>b)
            b=b-x;
            else
                a=a-x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if(a+x<=n)
        {
            if(a>b)
            a=a+x;
            else
                b=b+x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if(abs(a-b)>=x)
        {
            if(b<a)
            {
            x=x-b+1;
            b=1;
            a=a+x;
            }
            else
            {
                x=x-a+1;
                a=1;
                b=b+x;
            }
            cout<<abs(a-b)<<endl;
            continue;
        }
        else
        {
            cout<<n-1<<endl;
            continue;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(x==0)
        {
            cout<<a-b;
            continue;
        }
        if(b-x>=1)
        {
            b=b-x;
            cout<<a-b;
            continue;
        }
        else if(a+x<=n)
        {
            a=a+x;
            cout<<a-b;
            continue;
        }
        else if((a+x>n)&&(b-x<1)&&((n-a+b-1)>=x))
        {
            x=x-b+1;
            b=1;
            a=a+x;
            cout<<a-b;
            continue;
        }
        else
        {
            cout<<n-1;
            continue;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(x==0)
        {
            cout<<abs(a-b)<<endl;
            continue;
        }
        if(min(a,b)-x>=1)
        {
            if(a>b)
            b=b-x;
            else
                a=a-x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if(max(a,b)+x<=n)
        {
            if(a>b)
            a=a+x;
            else
                b=b+x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if((n-abs(a-b))>x)
        {
            if(b<a)
            {
            x=x-b+1;
            b=1;
            a=a+x;
            }
            else
            {
                x=x-a+1;
                a=1;
                b=b+x;
            }
            cout<<abs(a-b)<<endl;
            continue;
        }
        else
        {
            cout<<n-1<<endl;
            continue;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if(x==0)
        {
            cout<<abs(a-b)<<endl;
            continue;
        }
        if(b-x>=1)
        {
            if(a>b)
            b=b-x;
            else
                a=a-x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if(a+x<=n)
        {
            if(a>b)
            a=a+x;
            else
                b=b+x;
            cout<<abs(a-b)<<endl;
            continue;
        }
        else if(abs(n-(a-b))>=x)
        {
            if(b<a)
            {
            x=x-b+1;
            b=1;
            a=a+x;
            }
            else
            {
                x=x-a+1;
                a=1;
                b=b+x;
            }
            cout<<abs(a-b)<<endl;
            continue;
        }
        else
        {
            cout<<n-1<<endl;
            continue;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
int main(){

int a,b,c,d,i,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z;
cin>>t;
for(i=1;i<=t;i++){
   cin>>n>>x>>a>>b;

   d=abs(a-b);
   if(n==2){cout<<d<<endl;continue;}
   if((a==1||a==100)&& (b==1||b==100)){cout<<d<<endl;continue;}
   if((n!=2)|| (x<n) || (n<100) && (d<99)){
        d=d+x;
   if(d>99){d=99;}

   cout<<d<<endl;continue;}
   else{cout<<d<<endl;continue;}
   /*if(x==0){cout<<d<<endl;continue;}
   else if(a==1 && b==n){
        cout<<d<<endl;continue;
      }
    else if((x<n) || (a!=1) || (b!=n) || (n<100) ) { r=d+x;cout<<r<<endl;continue;}
   else{cout<<d<<endl;continue;}*/
}

return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){

int a,b,c,d,i,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z;
cin>>t;
for(i=1;i<=t;i++){
   cin>>n>>x>>a>>b;

   d=abs(a-b);
   if(n==2){cout<<d<<endl;continue;}
   if((a==1||a==100)&& (b==1||b==100)){cout<<d<<endl;continue;}
   if((n!=2)|| (x<n) || (n<100) && (d<99)){
        d=d+x;
   if(d>99){d=99;}
   if(d>=n){cout<<n-1<<endl;continue;}

   cout<<d<<endl;continue;}
   else{cout<<d<<endl;continue;}
   /*if(x==0){cout<<d<<endl;continue;}
   else if(a==1 && b==n){
        cout<<d<<endl;continue;
      }
    else if((x<n) || (a!=1) || (b!=n) || (n<100) ) { r=d+x;cout<<r<<endl;continue;}
   else{cout<<d<<endl;continue;}*/
}

return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){

int a,b,c,d,i,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z;
cin>>t;
for(i=1;i<=t;i++){
   cin>>n>>x>>a>>b;

   d=abs(a-b);
   if((a==1||a==100)&& (b==1||b==100)){cout<<d<<endl;continue;}
   if((x<n) || (n<100) && (d<99)){ d=d+x;cout<<d<<endl;continue;}
   else{cout<<d<<endl;continue;}
   /*if(x==0){cout<<d<<endl;continue;}
   else if(a==1 && b==n){
        cout<<d<<endl;continue;
      }
    else if((x<n) || (a!=1) || (b!=n) || (n<100) ) { r=d+x;cout<<r<<endl;continue;}
   else{cout<<d<<endl;continue;}*/
}

return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){

int a,b,c,d,i,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z;
cin>>t;
for(i=1;i<=t;i++){
   cin>>n>>x>>a>>b;

   d=abs(a-b);
   if((a==1||a==100)&& (b==1||b==100)){cout<<d<<endl;continue;}
   if((x<n) || (n<100) && (d<99)){
        d=d+x;
   if(d>99){d=99;}
   cout<<d<<endl;continue;}
   else{cout<<d<<endl;continue;}
   /*if(x==0){cout<<d<<endl;continue;}
   else if(a==1 && b==n){
        cout<<d<<endl;continue;
      }
    else if((x<n) || (a!=1) || (b!=n) || (n<100) ) { r=d+x;cout<<r<<endl;continue;}
   else{cout<<d<<endl;continue;}*/
}

return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){

int a,b,c,d,i,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z;
cin>>t;
for(i=1;i<=t;i++){
   cin>>n>>x>>a>>b;
   d=abs(a-b);
   if(x==0){cout<<d<<endl;continue;}
   else if(a==1 && b==n){
        cout<<d<<endl;continue;
      }
    else if((x<n) && (a!=1) && (b!=n) &&(n<100) ) { r=d+x;cout<<r<<endl;continue;}
   else{cout<<d<<endl;continue;}
}

return 0;
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, x, a, b;
		cin >> n >> x >> a >> b;
		 if (max(a, b) - min(a, b) +x> n-1) cout << max(a, b) - min(a, b) << endl;
		 if (max(a, b) - min(a, b) + x <= n - 1)  cout << max(a, b) - min(a, b) + x << endl;
	}
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, x, a, b;
		cin >> n >> x >> a >> b;
		 if (max(a, b) - min(a, b) +x>n-1) cout << max(max(a, b) - min(a, b),n-1) << endl;
		 if (max(a, b) - min(a, b) + x <= n - 1)  cout << max(a, b) - min(a, b) + x << endl;
	}
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, x, a, b;
		cin >> n >> x >> a >> b;
		 if (max(a, b) - min(a, b) +x>= n-1) cout << max(a, b) - min(a, b) << endl;
		 else  cout << max(a, b) - min(a, b)+x << endl;
	}
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, x, a, b;
		cin >> n >> x >> a >> b;
		 if (max(a, b) - min(a, b) +x> n-1) cout << max(a, b) - min(a, b) << endl;
		 else  cout << max(a, b) - min(a, b)+x << endl;
	}
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, x, a, b;
		cin >> n >> x >> a >> b;
		 if (max(a, b) - min(a, b) +x>= n-1) cout << max(a, b) - min(a, b) << endl;
		 if (max(a, b) - min(a, b) + x <= n - 1)  cout << max(a, b) - min(a, b) + x << endl;
	}
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, x, a, b;
		cin >> n >> x >> a >> b;
		if(x==0) cout<< max(a, b) - min(a, b) << endl;
		else if (max(a, b) - min(a, b) +x>= n) cout << max(a, b) - min(a, b) << endl;
		     else  cout << max(a, b) - min(a, b)+x << endl;
	}
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, x, a, b;
		cin >> n >> x >> a >> b;
		if(x==0) cout<< max(a, b) - min(a, b) << endl;
		else if (max(a, b) - min(a, b) +x> n) cout << max(a, b) - min(a, b) << endl;
		     else  cout << max(a, b) - min(a, b)+x << endl;
	}
}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int result(int a, int b, int n, int x){
           if(a>b){
                if(a==n){
                    if(b<x){
                        cout<<n-1<<endl;
                    }
                    else{
                        cout<<a-(b-x)<<endl;
                    }
                }
                else{
                    if(a+x>n){
                        a==n;
                        x=x-(n-a);
                        if(b<x){
                            b==1;
                            cout<<abs(a-b)<<'\n';
                        }
                        else{
                            b=b-x;
                            cout<<a-b<<endl;
                        }
                    }
                    else{
                        a=a+x;
                        cout<<a-b<<'\n';
                    }
                }
            }
}
int main(int argc, char **argv)
{
    int t;
    cin>>t;
    while(t--){
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if((a==n && b==1) || (a==1 && b==n)){
            cout<<abs(a-b)<<'\n';
        }
        else{
            if(a>=b){
                result(a,b,n,x);
            }
            else{
                swap(a,b);
                result(a,b,n,x);
            }
        }
    }
    return 0;
}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int result(int a, int b, int n, int x){
           if(a>b){
                if(a==n){
                    if(b<x){
                        cout<<n-1<<endl;
                    }
                    else{
                        cout<<a-(b-x)<<endl;
                    }
                }
                else{
                    if(a+x>=n){
                        a==n;
                        x=x-(n-a);
                        if(b<x){
                            b==1;
                            cout<<abs(a-b)<<'\n';
                        }
                        else{
                            b=b-x;
                            cout<<a-b<<endl;
                        }
                    }
                    else{
                        a=a+x;
                        cout<<a-b<<'\n';
                    }
                }
            }
}
int main(int argc, char **argv)
{
    int t;
    cin>>t;
    while(t--){
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if((a==n && b==1) || (a==1 && b==n)){
            cout<<abs(a-b)<<'\n';
        }
        else{
            if(a>=b){
                result(a,b,n,x);
            }
            else{
                swap(a,b);
                result(a,b,n,x);
            }
        }
    }
    return 0;
}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int result(int a, int b, int n, int x){
           if(a>b){
                if(a==n){
                    if(b<x){
                        cout<<n-1<<endl;
                    }
                    else{
                        cout<<a-(b-x)<<endl;
                    }
                }
                else{
                    if(a+x>n){
                        a==n;
                        x=x-(n-a);
                        if(b<x){
                            b==1;
                            cout<<n-1<<'\n';
                        }
                        else{
                            b=b-x;
                            cout<<a-b<<endl;
                        }
                    }
                    else{
                        a=a+x;
                        cout<<a-b<<'\n';
                    }
                }
            }
}
int main(int argc, char **argv)
{
    int t;
    cin>>t;
    while(t--){
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if((a==n && b==1) || (a==1 && b==n)){
            cout<<abs(a-b)<<'\n';
        }
        else{
            if(a>=b){
                result(a,b,n,x);
            }
            else{
                swap(a,b);
                result(a,b,n,x);
            }
        }
    }
    return 0;
}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int result(int n, int x, int a, int b){
    int bel=0;
                if(a==n){
                    if(b<x){
                        cout<<n-1<<endl;
                    }
                    else{
                        cout<<a-(b-x)<<endl;
                    }
                }
                else{
                    if(a+x>n){
                        a==n;
                        x=x-(n-a);
                        if(b<=x){
                            b==1;
                            cout<<n-1<<'\n';
                        }
                        else if(b>x){
                            bel=b-x;
                            cout<<n-bel<<endl;
                        }
                    }
                    else{
                        a=a+x;
                        cout<<a-b<<'\n';
                    }
                }
}
int main(int argc, char **argv)
{
    int t;
    cin>>t;
    while(t--){
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if((a==n && b==1) || (a==1 && b==n)){
            cout<<abs(a-b)<<'\n';
        }
        else{
            if(a>=b){
                result(n,x,a,b);
            }
            else{
                swap(a,b);
                result(n,x,a,b);
            }
        }
    }
    return 0;
}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int result(int n, int x, int a, int b){
    int bel=0;
                    if(a+x>n){
                        a==n;
                        x=x-(n-a);
                        if(b<=x){
                            b==1;
                            cout<<n-1<<'\n';
                        }
                        else if(b>x){
                            bel=b-x;
                            cout<<n-bel<<endl;
                        }
                    }
                    else{
                        a=a+x;
                        cout<<a-b<<'\n';
                    }
}
int main(int argc, char **argv)
{
    int t;
    cin>>t;
    while(t--){
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if((a==n && b==1) || (a==1 && b==n)){
            cout<<abs(a-b)<<'\n';
        }
        else{
            if(a>=b){
                result(n,x,a,b);
            }
            else{
                swap(a,b);
                result(n,x,a,b);
            }
        }
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int t,n,x,a,b;
main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d%d%d%d",&n,&x,&a,&b);
        if(a>b) swap(a,b);
        if(a-x>1){
            a-=x;
            x=0;
        }
        else if(a-x<1){
            a=1;
            x=x-a;
        }
        if(x>0 && b+x<n){
            b+=x;
        }
        else if(b+x>=n){
            b=n;
        }
        printf("%d\n",abs(b-a));
    }
}


#include<bits/stdc++.h>
using namespace std;
int t,n,x,a,b;
main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d%d%d%d",&n,&x,&a,&b);
        if(a>b) swap(a,b);
        if(a-x>1){
            a-=x;
            x=0;
        }
        else if(a-x<=1){
            a=1;
            x-=a;
        }
        if(x>0 && b+x<n){
            b+=x;
            x=0;
        }
        else if(b+x>=n){
            b=n;
        }
        printf("%d\n",abs(b-a));
    }
}


#include<bits/stdc++.h>
using namespace std;
int t,n,x,a,b;
main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d%d%d%d",&n,&x,&a,&b);
        if(a>b) swap(a,b);
        if(a-x>=1){
            a-=x;
            x=0;
        }
        else if(a-x<1 && a!=1 && x>0){
            x=x-a+1;
            a=1;
        }
        if(x>0 && b+x<n){
            b+=x;
        }
        else if(b+x>=n && x>0){
            b=n;
        }
        printf("%d\n",abs(b-a));
    }
}


#include<bits/stdc++.h>
using namespace std;
int t,n,x,a,b;
main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d%d%d%d",&n,&x,&a,&b);
        if(a>b) swap(a,b);
        if(a-x>1){
            a-=x;
            x=0;
        }
        else if(a-x<=1){
            a=1;
            x=x-a+1;
        }
        if(x>0 && b+x<n){
            b+=x;
        }
        else if(b+x>=n){
            b=n;
        }
        printf("%d\n",abs(b-a));
    }
}


#include<bits/stdc++.h>
using namespace std;
int t,n,x,a,b;
main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d%d%d%d",&n,&x,&a,&b);
        if(a>b) swap(a,b);
        if(a-x>=1){
            a-=x;
            x=0;
        }
        else if(a-x<1 && a!=1){
            a=1;
            x=x-a;
        }
        if(x>0 && b+x<n){
            b+=x;
        }
        else if(b+x>=n){
            b=n;
        }
        printf("%d\n",abs(b-a));
    }
}


#include<bits/stdc++.h>
using namespace std;
int t,n,x,a,b;
main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d%d%d%d",&n,&x,&a,&b);
        if(a>b) swap(a,b);
        if(a-x>1){
            a-=x;
            x=0;
        }
        else if(a-x<1 && a!=1){
            a=1;
            x=x-a;
        }
        if(x>0 && b+x<n){
            b+=x;
        }
        else if(b+x>=n){
            b=n;
        }
        printf("%d\n",abs(b-a));
    }
}


#include<bits/stdc++.h>
using namespace std;
int t,n,x,a,b;
main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d%d%d%d",&n,&x,&a,&b);
        if(a>b) swap(a,b);
        if(a-x>=1){
            a-=x;
            x=0;
        }
        else if(a-x<1 && a!=1){
            a=1;
            x=x-a+1;
        }
        if(x>0 && b+x<n){
            b+=x;
        }
        else if(b+x>=n){
            b=n;
        }
        printf("%d\n",abs(b-a));
    }
}


#include<iostream>

using namespace std;

int main(){
    int t;
    cin>>t;
    for(int z =0;z<t;z++){
        int a,b,x,s,r,k;
        cin>>r>>x>>b>>a;
        s = (a>b?a:b);
        k = (a>b?b:a);
        while(r>s && x){
            ++s;
            --x;
        }
        while(x && k>1){
            --k;
            --x;
        }
        cout<<s-k;
    }
    return 0;
}


#include<iostream>

using namespace std;

int main(){
    int t;
    cin>>t;
    for(int z =0;z<t;z++){
        int a,b,x,s,r,k;
        cin>>r>>x>>b>>a;
        s = (a>b?a:b);
        k = (a>b?b:a);
        for(int i =0;i<x;i++){
            ++s;
        }
        if (s>r){
        k = k - (r-s);
        if(k<1) k =1;
        }
        cout<<s-(a<b?a:b);
    }
    return 0;
}


#include<iostream>

using namespace std;

int main(){
    int t;
    cin>>t;
    for(int z =0;z<t;z++){
        int a,b,x,s,r;
        cin>>r>>x>>b>>a;
        s = (a>b?a:b);
        for(int i =0;i<x;i++){
            s = (s+1);
            if(s>r){
                s = r;
            }
        }
        cout<<s-(a<b?a:b);
    }
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

int main(){
    int t;
    cin>>t;
    while(t--){
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if((abs(b-a)+x) > n)
            cout<<n-1;
        else
            cout<<(abs(b-a)+x);
    }
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

int main(){
    int t;
    cin>>t;
    while(t--){
        int n,x,a,b;
        cin>>n>>x>>a>>b;
        if((abs(b-a)+x) > n)
            cout<<n-1<<endl;;
        else
            cout<<(abs(b-a)+x)<<endl;
    }
    return 0;
}


#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;

long long data[2010];
long long _next[2010];
vector<pair<int, int>> edges[2010];
long long v[2010];
const int MOD = 1000000007;

void getNext(int n) {
	memset(_next, -1, sizeof(_next));
	for (int i = 1;i <= n;i++) {
		if (data[i] == -1) {
			continue;
		}
		for (int j = 0;j < edges[i].size();j++) {
			int y = edges[i][j].first;
			int w = edges[i][j].second;
			if (_next[y] == -1 || _next[y] < data[i] + w) {
				_next[y] = data[i] + w;
			}
		}
	}
}

long long getMax(int n) {
	long long ret = -1;
	for (int i = 1;i <= n;i++) {
		if (data[i] == -1) {
			continue;
		}
		if (ret == -1 || ret < data[i]) {
			ret = data[i];
		}
	}
	return ret;
}

int main() {
	int n, m, q;
	scanf("%d%d%d", &n, &m, &q);
	memset(data, -1, sizeof(data));
	data[1] = 0;
	for (int i = 0;i < m;i++) {
		int x, y, w;
		scanf("%d%d%d", &x, &y, &w);
		edges[x].push_back(make_pair(y, w));
		edges[y].push_back(make_pair(x, w));
	}
	long long ret = 0;
	int i = 0;
	for (;i < 2 * n && i < q;i++) {
		getNext(n);
		memcpy(data, _next, sizeof(data));
		ret += getMax(n);
		ret %= MOD;
	}
	int now = 2 * n + 1;
	if (i == q) {
		printf("%d\n", ret);
	} else {
		for (int i = 1;i < n;i++) {
			v[i] = -1;
			for (int j = 0;j < edges[i].size();j++) {
				if (v[i] == -1 || v[i] < edges[i][j].second) {
					v[i] = edges[i][j].second;
				}
			}
			data[i] += v[i];
		}
		while (now <= q) {
			int index = 1;
			for (int i = 2;i <= n;i++) {
				if (data[i] > data[index] || (data[i] == data[index] && v[i] > v[index])) {
					index = i;
				}
			}
			int last = -1;
			for (int i = 1;i <= n;i++) {
				if (index == i) {
					continue;
				}
				if (v[i] <= v[index]) {
					continue;
				}
				int t = (data[index] - data[i]) / (v[i] - v[index]);
				if ((data[index] - data[i]) % (v[i] - v[index]) == 0) {
					t++;
				}
				if (last == -1 || last > t) {
					last = t;
				}
			}
			if (last == -1) {
				last = q;
			}
			if (last > q) {
				last = q;
			}
			ret += data[index] * (last - now + 1) + v[index] * (last - now) * (last - now + 1) / 2;
			ret %= MOD;
			for (int i = 1;i <= n;i++) {
				data[i] += (last - now) * v[i];
			}
			now = last + 1;
		}
		printf("%d\n", ret);
	}

	return 0;
}