Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers li and ri for each of the days — the indices of socks to wear on the day i (obviously, li stands for the left foot and ri for the right). Each sock is painted in one of k colors.When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paint — one for each of k colors.Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.

The first line of input contains three integers n, m and k (2 ≤ n ≤ 200 000, 0 ≤ m ≤ 200 000, 1 ≤ k ≤ 200 000) — the number of socks, the number of days and the number of available colors respectively. The second line contain n integers c1, c2, ..., cn (1 ≤ ci ≤ k) — current colors of Arseniy's socks. Each of the following m lines contains two integers li and ri (1 ≤ li, ri ≤ n, li ≠ ri) — indices of socks which Arseniy should wear during the i-th day.

Print one integer — the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.

NoteIn the first sample, Arseniy can repaint the first and the third socks to the second color.In the second sample, there is no need to change any colors.

var fuck = readline().split(' ').map(x => parseInt(x))
var n = fuck[0], m = fuck[1], k = fuck[2], i, v = [], a = []
fuck = readline().split(' ').map(x => parseInt(x))

a.push(0)
for (i = 0; i < n; i++) a.push(fuck[i])
for (i = 0; i < m; i++) {
    fuck = readline().split(' ').map(x => parseInt(x))
    if (typeof v[fuck[0]] === "undefined") v[fuck[0]] = []
    if (typeof v[fuck[1]] === "undefined") v[fuck[1]] = []
    v[fuck[0]].push(fuck[1]), v[fuck[1]].push(fuck[0])
}
var vis = [], mem = [], ans = 0, union = [], root = []
for (i = 0; i <= n; i++) {
    root.push(i)
    union.push([i])
    vis.push(false)
}
var q = [], top
for (i = 1; i <= n; i++) {
    if (!vis[i]) {
        q.push(i)
        while (q.length > 0) {
            top = q.pop()
            if (!vis[top]) {
                vis[top] = true
                if (typeof v[top] !== "undefined")
                    for (var j of v[top]) {
                        if (root[j] > root[i] && !vis[j]) {
                            root[j] = root[i]
                            union[root[i]].push(j)
                            q.push(j)
                        }
                    }
            }
        }
    }
}
for (i = 1; i <= n; i++) {
    if (root[i] === i) {
        mem = []
        for (var j of union[i]) {
            if (typeof mem[a[j]] === 'undefined') mem[a[j]] = 0
            mem[a[j]]++
        }
        mem.sort((x, y) => y - x)
        ans += union[i].length - mem[0]
    }
}
print(ans)

var fuck = readline().split(' ').map(x => parseInt(x))
var n = fuck[0], m = fuck[1], k = fuck[2], i, v = [], a = []
fuck = readline().split(' ').map(x => parseInt(x))

a.push(0)
for (i = 0; i < n; i++) a.push(fuck[i])
for (i = 0; i < m; i++) {
    fuck = readline().split(' ').map(x => parseInt(x))
    if (typeof v[fuck[0]] === "undefined") v[fuck[0]] = []
    if (typeof v[fuck[1]] === "undefined") v[fuck[1]] = []
    v[fuck[0]].push(fuck[1]), v[fuck[1]].push(fuck[0])
}
var vis = [], mem = [], ans = 0, union = [], root = []
for (i = 0; i <= n; i++) {
    root.push(i)
    union.push([i])
    vis.push(false)
}
for (i = 1; i <= n; i++) {
    if (typeof v[i] !== "undefined") {
        for (var j of v[i]) {
            if (root[j] > root[i] && !vis[j]) {
                vis[j] = true
                root[j] = root[i]
                union[root[i]].push(j)
            }
        }
    }
}
for (i = 1; i <= n; i++) {
    if (root[i] === i) {
        mem = []
        for (var j of union[i]) {
            if (typeof mem[a[j]] === 'undefined') mem[a[j]] = 0
            mem[a[j]]++
        }
        mem.sort((x, y) => y - x)
        ans += union[i].length - mem[0]
    }
}
print(ans)

var fuck = readline().split(' ').map(x => parseInt(x))
var n = fuck[0], m = fuck[1], k = fuck[2], i, v = [], a = []
fuck = readline().split(' ').map(x => parseInt(x))

a.push(0)
for (i = 0; i < n; i++) a.push(fuck[i])
for (i = 0; i < m; i++) {
    fuck = readline().split(' ').map(x => parseInt(x))
    if (typeof v[fuck[0]] === "undefined") v[fuck[0]] = []
    if (typeof v[fuck[1]] === "undefined") v[fuck[1]] = []
    v[fuck[0]].push(fuck[1]), v[fuck[1]].push(fuck[0])
}
var mem = [], ans = 0, union = [], root = []
for (i = 0; i <= n; i++) {
    root.push(i)
    union.push([i])
}
for (i = 1; i <= n; i++) {
    if (typeof v[i] !== "undefined") {
        for (var j of v[i]) {
            if (j > i) {
                root[j] = root[i]
                union[root[i]].push(j)
            }
        }
    }
}
for (i = 1; i <= n; i++) {
    if (root[i] === i) {
        mem = []
        for (var j of union[i]) {
            if (typeof mem[a[j]] === 'undefined') mem[a[j]] = 0
            mem[a[j]]++;
        }
        mem.sort((x, y) => y - x)
        ans += union[i].length - mem[0]

    }
}
print(ans)

var fuck = readline().split(' ').map(x => parseInt(x))
var n = fuck[0], m = fuck[1], k = fuck[2], i, v = [], a = []
fuck = readline().split(' ').map(x => parseInt(x))

a.push(0)
for (i = 0; i < n; i++) a.push(fuck[i])
for (i = 0; i < m; i++) {
    fuck = readline().split(' ').map(x => parseInt(x))
    if (typeof v[fuck[0]] === "undefined") v[fuck[0]] = []
    if (typeof v[fuck[1]] === "undefined") v[fuck[1]] = []
    v[fuck[0]].push(fuck[1]), v[fuck[1]].push(fuck[0])
}
var vis = [], mem = [], ans = 0, union = [], root = []
for (i = 0; i <= n; i++) {
    root.push(i)
    union.push([i])
    vis.push(false)
}
for (i = 1; i <= n; i++) {
    vis[i] = true
    if (typeof v[i] !== "undefined") {
        for (var j of v[i]) {
            if (j > i && !vis[j]) {
                vis[j] = true
                root[j] = root[i]
                union[root[i]].push(j)
            }
        }
    }
}
for (i = 1; i <= n; i++) {
    if (root[i] === i) {
        mem = []
        for (var j of union[i]) {
            if (typeof mem[a[j]] === 'undefined') mem[a[j]] = 0
            mem[a[j]]++;
        }
        mem.sort((x, y) => y - x)
        ans += union[i].length - mem[0]

    }
}
print(ans)

var fuck = readline().split(' ').map(x => parseInt(x))
var n = fuck[0], m = fuck[1], k = fuck[2], i, v = [], a = []
fuck = readline().split(' ').map(x => parseInt(x))

a.push(0)
for (i = 0; i < n; i++) a.push(fuck[i])
for (i = 0; i < m; i++) {
    fuck = readline().split(' ').map(x => parseInt(x))
    if (typeof v[fuck[0]] === "undefined") v[fuck[0]] = []
    if (typeof v[fuck[1]] === "undefined") v[fuck[1]] = []
    v[fuck[0]].push(fuck[1]), v[fuck[1]].push(fuck[0])
}
var vis = [], mem = [], ans = 0, union = [], root = []
for (i = 0; i <= n; i++) {
    root.push(i)
    union.push([i])
    vis.push(false)
}
for (i = 1; i <= n; i++) {
    vis[i] = true
    if (typeof v[i] !== "undefined") {
        for (var j of v[i]) {
            if (j > i && !vis[j]) {
                vis[j] = true
                root[j] = root[i]
                union[root[i]].push(j)
            }
        }
    }
}
for (i = 1; i <= n; i++) {
    if (root[i] === i) {
        mem = []
        mem[a[i]] = 1
        for (var j of union[i]) {
            if (typeof mem[a[j]] === 'undefined') mem[a[j]] = 0
            mem[a[j]]++
        }
        mem.sort((x, y) => y - x)
        ans += union[i].length - mem[0]
    }
}
print(ans)


Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.Consider that m (m ≤ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.After occupying all the window seats (for m > 2n) the non-window seats are occupied:1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat.  The seating for n = 9 and m = 36. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.

The only line contains two integers, n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 4n) — the number of pairs of rows and the number of passengers.

Print m distinct integers from 1 to m — the order in which the passengers will get off the bus.

var arr = readline().split(' ').map(i=>+i);
var n = arr[0];
var m = arr[1];

var out = [];
for (var i = 1; i <= m; i++) {
    if (i/2 < m-2*n && i % 2 === 1) {
        out.push(2*n + Math.ceil(i/2));
    } else if(i/2 < m-2*n && i % 2 === 0) {
        out.push(i/2);
    } else {
        if (m >= 2*n) out.push(i - (m-2*n));
        else out.push(i);
    }
}

print(out.join(' '));

var arr = readline().split(' ').map(i=>+i);
var n = arr[0];
var m = arr[1];

var i = 0;
var out = [];
for (var i = 1; i <= m; i++) {
    if (i/2 < m-2*n && i % 2 === 1) {
        out.push(2*n + Math.ceil(i/2));
    } else if(i/2 < m-2*n && i % 2 === 0) {
        out.push(i/2);
    } else {
        out.push(i - (m-2*n));
    }
}

print(out.join(' '));


You are given a sequence $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, and an integer $$$x$$$. Your task is to make the sequence $$$a$$$ sorted (it is considered sorted if the condition $$$a_1 \le a_2 \le a_3 \le \dots \le a_n$$$ holds).To make the sequence sorted, you may perform the following operation any number of times you want (possibly zero): choose an integer $$$i$$$ such that $$$1 \le i \le n$$$ and $$$a_i > x$$$, and swap the values of $$$a_i$$$ and $$$x$$$.For example, if $$$a = [0, 2, 3, 5, 4]$$$, $$$x = 1$$$, the following sequence of operations is possible:  choose $$$i = 2$$$ (it is possible since $$$a_2 > x$$$), then $$$a = [0, 1, 3, 5, 4]$$$, $$$x = 2$$$;  choose $$$i = 3$$$ (it is possible since $$$a_3 > x$$$), then $$$a = [0, 1, 2, 5, 4]$$$, $$$x = 3$$$;  choose $$$i = 4$$$ (it is possible since $$$a_4 > x$$$), then $$$a = [0, 1, 2, 3, 4]$$$, $$$x = 5$$$. Calculate the minimum number of operations you have to perform so that $$$a$$$ becomes sorted, or report that it is impossible.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500$$$, $$$0 \le x \le 500$$$) — the number of elements in the sequence and the initial value of $$$x$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 500$$$). The sum of values of $$$n$$$ over all test cases in the input does not exceed $$$500$$$.

For each test case, print one integer — the minimum number of operations you have to perform to make $$$a$$$ sorted, or $$$-1$$$, if it is impossible.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    let [len, lastItem] = readLine().split(" ").map(Number);
    const arr = readLine().split(" ").map(Number);
    if (isSorted(arr) || len === 1) console.log(0);
    else {
      let count = 0;
      for (let i = 0; i < len; i++) {
        const current = arr[i];
        if (current > lastItem) {
          [arr[i], lastItem] = [lastItem, arr[i]];
          count++;
          if (isSorted(arr)) break;
        }
      }
      if (isSorted(arr)) console.log(count);
      else console.log(-1);
    }
    function isSorted(arr) {
      let sorted = true;
      for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i + 1]) {
          sorted = false;
          break;
        }
      }
      return sorted;
    }
  }
}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;i<t;++i){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const i=n(r(747));let o="",s=[],u=0,l="";const f="local"===process.argv[2],p=t=>{if(f){if(s=i.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),i.default.writeFileSync("output.txt",l),console.log(l),i.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{s=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function a(){return s[u++]}function h(){return a().split(" ").map((t=>parseFloat(t)))}function c(){return a().split("")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:a,nextNumbers:h,nextBigNumbers:function(){return a().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(h());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=h();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){f&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const i=n(r(312));i.default.runEachTest((function(){let[t,e]=i.default.nextNumbers(),r=i.default.nextNumbers(),n=0;for(let o=0;o<t-1;++o){if(r[o]>r[o+1]){if(!(r[o+1]>=e))return void i.default.puts(-1);{for(let t=0;t<o;++t)if(r[t]>e){let i=r[t];r[t]=e,e=i,n++}let t=r[o];r[o]=e,e=t,n++}}if(r[o]>r[o+1]){if(e>r[o+1])return void i.default.puts(-1);let t=r[o+1];r[o+1]=e,e=t,n++}}i.default.puts(n)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n, x] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let swaps = 0
//
//   for (let i = 0; i < n - 1; ++i) {
//     if (a[i] > a[i + 1]) {
//       // try to fix
//
//       if (a[i + 1] >= x) {
//         for (let j = 0; j < i; ++j) {
//           if (a[j] > x) {
//             let t = a[j]
//             a[j] = x
//             x = t
//             swaps++
//           }
//         }
//         let t = a[i]
//         a[i] = x
//         x = t
//         swaps++
//       } else {
//         io.puts(-1)
//         return
//       }
//     }
//
//     // io.debug(a)
//
//     if (a[i] > a[i + 1]) {
//       if (x > a[i + 1]) {
//         io.puts(-1)
//         return
//       }
//
//       let t = a[i + 1]
//       a[i + 1] = x
//       x = t
//       swaps++
//     }
//   }
//
//   io.puts(swaps)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;i<t;++i){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const i=n(r(747));let o="",s=[],u=0,l="";const f="local"===process.argv[2],p=t=>{if(f){if(s=i.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),i.default.writeFileSync("output.txt",l),console.log(l),i.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{s=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function a(){return s[u++]}function h(){return a().split(" ").map((t=>parseFloat(t)))}function c(){return a().split("")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:a,nextNumbers:h,nextBigNumbers:function(){return a().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(h());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=h();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){f&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const i=n(r(312));i.default.runEachTest((function(){let[t,e]=i.default.nextNumbers(),r=i.default.nextNumbers(),n=0;for(let o=0;o<t-1;++o){if(r[o]>r[o+1]){if(!(r[o+1]>=e))return void i.default.puts(-1);{for(let t=0;t<o;++t)if(r[t]>e){let i=r[t];r[t]=e,e=i,n++}let t=r[o];r[o]=e,e=t,n++}}if(r[o]>r[o+1]&&e>r[o+1])return void i.default.puts(-1)}i.default.puts(n)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n, x] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let swaps = 0
//
//   for (let i = 0; i < n - 1; ++i) {
//     if (a[i] > a[i + 1]) {
//       // try to fix
//
//       if (a[i + 1] >= x) {
//         for (let j = 0; j < i; ++j) {
//           if (a[j] > x) {
//             let t = a[j]
//             a[j] = x
//             x = t
//             swaps++
//           }
//         }
//         let t = a[i]
//         a[i] = x
//         x = t
//         swaps++
//       } else {
//         io.puts(-1)
//         return
//       }
//     }
//
//     // io.debug(a)
//
//     if (a[i] > a[i + 1]) {
//       if (x > a[i + 1]) {
//         io.puts(-1)
//         return
//       }
//
//       // let t = a[i + 1]
//       // a[i + 1] = x
//       // x = t
//       // swaps++
//     }
//   }
//
//   io.puts(swaps)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

/*
 * File Created: Monday, 30th November 2020 3:31:00 pm
 * Author: Lukas Rimkus
 */

'use-strict'

const { count } = require("console");

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

process.stdin.on('data', chunk => {
data += chunk;
});

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const n = data.shift().split(' ').map(Number);

        const arr = data.shift().split(' ').map(Number);

        const res = d(n[0], n[1], arr);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

function readLine() {
        return data[currentLine++];
}

function a(num)
{
    return num.length ;
}

function b(goal)
{

    function jump1(y,k)
    {
        return y + k;
    }
    function jump2(y)
    {
        return y - 1;
    }

    let sum = 0;

    let jumps = 0;

    let arr = [];

    while(sum < goal)
    {
        jumps++;

        arr.push(jumps);

        sum = sum + jumps;
    }

    if(sum === goal)
    {
        return arr.length;
    }
    else
    {
        let current_pos = sum;

        // that's how many steps back;
        let diference = current_pos - goal;

        console.log(arr, arr.length, sum, diference)

        for(let i = 0 ; i < arr.length; i++)
        {
            if((arr[i] + 1) === diference)
            {
                return arr.length;
            }
        }
       return arr.length + 1;
    }
}

function c(x,y)
{
    const arr = new Array(2);

    arr[0] = x - 1;

    arr[1] = y
    return arr;
}

function help(a)
{
    for(let i = 0; i < a.length; i++)
    {
        if(a[i] > a[i + 1])
        {
            return false;
        }
    }
    return true;
}

function d(n, x, arr)
{
    let count = 0 ;

    if(n === 1 || help(arr))
    {
        return 0;
    }

    for(let i = 0 ; i < arr.length; i++)
    {
        const current = arr[i];

        if(current > x)
        {
            [arr[i], x] = [x, arr[i]];

            count++;
        }
        if(help(arr))
        {
            return count;
        }
    }
    return  -1;
}

module.exports = d;

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [len, lastItem] = readLine().split(" ").map(Number);
    const arr = readLine().split(" ").map(Number);
    if (isSorted(arr) || len === 1) console.log(0);
    else {
      arr.push(lastItem);
      let count = 0;
      for (let i = 0; i < len; i++) {
        const [last, current] = [arr[len], arr[i]];
        if (current > last) {
          [arr[len], arr[i]] = [current, last];
          count++;
          if (isSorted(arr)) break;
        }
      }
      if (isSorted(arr)) console.log(count);
      else console.log(-1);
    }
    function isSorted(arr) {
      let sorted = true;
      for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i + 1]) {
          sorted = false;
          break;
        }
      }
      return sorted;
    }
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [len, lastItem] = readLine().split(" ").map(Number);
    const arr = readLine().split(" ").map(Number);
    if (isSorted(arr) || len === 1) console.log(0);
    else {
      arr.push(lastItem);
      let count = 0;
      for (let i = 0; i < len; i++) {
        const [last, current] = [arr[len], arr[i]];
        if (current > last) {
          [arr[len], arr[i]] = [current, last];
          count++;
        }
      }
      if (isSorted(arr)) console.log(count);
      else console.log(-1);
    }
    function isSorted(arr) {
      let sorted = true;
      for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i + 1]) {
          sorted = false;
          break;
        }
      }
      return sorted;
    }
  }
}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;i<t;++i){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const i=n(r(747));let o="",s=[],u=0,l="";const p="local"===process.argv[2],f=t=>{if(p){if(s=i.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),i.default.writeFileSync("output.txt",l),console.log(l),i.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{s=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function a(){return s[u++]}function h(){return a().split(" ").map((t=>parseFloat(t)))}function c(){return a().split("")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:a,nextNumbers:h,nextBigNumbers:function(){return a().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(h());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=h();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){p&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const i=n(r(312));i.default.runEachTest((function(){let[t,e]=i.default.nextNumbers(),r=i.default.nextNumbers(),n=0;for(let o=0;o<t-1;++o)if(r[o]>r[o+1]){if(!(r[o+1]>=e))return void i.default.puts(-1);{for(let t=0;t<o;++t)if(r[t]>e){let i=r[t];r[t]=e,e=i,n++}let t=r[o];r[o]=e,e=t,n++}}i.default.puts(n)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n, x] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let swaps = 0
//
//   for (let i = 0; i < n - 1; ++i) {
//     if (a[i] > a[i + 1]) {
//       // try to fix
//
//       if (a[i + 1] >= x) {
//         for (let j = 0; j < i; ++j) {
//           if (a[j] > x) {
//             let t = a[j]
//             a[j] = x
//             x = t
//             swaps++
//           }
//         }
//         let t = a[i]
//         a[i] = x
//         x = t
//         swaps++
//       } else {
//         io.puts(-1)
//         return
//       }
//     }
//   }
//
//   io.puts(swaps)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;i<t;++i){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const i=n(r(747));let o="",s=[],u=0,l="";const f="local"===process.argv[2],p=t=>{if(f){if(s=i.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),i.default.writeFileSync("output.txt",l),console.log(l),i.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{s=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function a(){return s[u++]}function h(){return a().split(" ").map((t=>parseFloat(t)))}function c(){return a().split("")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:a,nextNumbers:h,nextBigNumbers:function(){return a().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(h());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=h();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){f&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const i=n(r(312));i.default.runEachTest((function(){let[t,e]=i.default.nextNumbers(),r=i.default.nextNumbers(),n=0;for(let o=0;o<t-1;++o){if(r[o]>r[o+1]){if(!(r[o+1]>=e))return void i.default.puts(-1);{for(let t=0;t<o;++t)if(r[t]>e){let i=r[t];r[t]=e,e=i,n++}let t=r[o];r[o]=e,e=t,n++}}if(i.default.debug(r),r[o]>r[o+1]){let t=r[o+1];r[o+1]=e,e=t,n++}}i.default.puts(n)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n, x] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let swaps = 0
//
//   for (let i = 0; i < n - 1; ++i) {
//     if (a[i] > a[i + 1]) {
//       // try to fix
//
//       if (a[i + 1] >= x) {
//         for (let j = 0; j < i; ++j) {
//           if (a[j] > x) {
//             let t = a[j]
//             a[j] = x
//             x = t
//             swaps++
//           }
//         }
//         let t = a[i]
//         a[i] = x
//         x = t
//         swaps++
//       } else {
//         io.puts(-1)
//         return
//       }
//     }
//
//     io.debug(a)
//
//     if (a[i] > a[i + 1]) {
//       let t = a[i + 1]
//       a[i + 1] = x
//       x = t
//       swaps++
//     }
//   }
//
//   io.puts(swaps)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;i<t;++i){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const i=n(r(747));let o="",s=[],u=0,l="";const f="local"===process.argv[2],p=t=>{if(f){if(s=i.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),i.default.writeFileSync("output.txt",l),console.log(l),i.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{s=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function a(){return s[u++]}function h(){return a().split(" ").map((t=>parseFloat(t)))}function c(){return a().split("")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:a,nextNumbers:h,nextBigNumbers:function(){return a().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(h());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=h();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){f&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const i=n(r(312));i.default.runEachTest((function(){let[t,e]=i.default.nextNumbers(),r=i.default.nextNumbers(),n=0;for(let o=0;o<t-1;++o)if(r[o]>r[o+1]){if(!(r[o+1]>=e))return void i.default.puts(-1);{for(let t=0;t<o;++t)if(r[t]>e){let i=r[t];r[t]=e,e=i,n++}let t=r[o];if(r[o]=e,e=t,n++,e>r[o+1])return void i.default.puts(-1)}}i.default.puts(n)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n, x] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let swaps = 0
//
//   for (let i = 0; i < n - 1; ++i) {
//     if (a[i] > a[i + 1]) {
//       // try to fix
//
//       if (a[i + 1] >= x) {
//         for (let j = 0; j < i; ++j) {
//           if (a[j] > x) {
//             let t = a[j]
//             a[j] = x
//             x = t
//             swaps++
//           }
//         }
//         let t = a[i]
//         a[i] = x
//         x = t
//         swaps++
//
//         if (x > a[i + 1]) {
//           io.puts(-1)
//           return
//         }
//       } else {
//         io.puts(-1)
//         return
//       }
//     }
//   }
//
//   io.puts(swaps)
// }
//
// io.runEachTest(main)
// // io.runMain(main)


Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all $$$26$$$ lowercase Latin letters will be arranged in some order.Polycarp uses the same password $$$s$$$ on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in $$$s$$$, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in $$$s$$$, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Then $$$T$$$ lines follow, each containing one string $$$s$$$ ($$$1 \le |s| \le 200$$$) representing the test case. $$$s$$$ consists of lowercase Latin letters only. There are no two adjacent equal characters in $$$s$$$.

For each test case, do the following:   if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of $$$26$$$ lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them.

5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza

YES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

'use strict'

const problem = (s) => {
    if (s.length < 2) return 'YES\nabcdefghijklmnopqrstuvwxyz';
    if (s.length === 2) return 'YES\n' + s + 'abcdefghijklmnopqrstuvwxyz'.replace(s[0], '').replace(s[1], '')
    let a = [ s[0], s[1] ];
    let j = 1;
    for (let i = 2; i < s.length; i++) {
        const next = s[i];
        const l = a[j-1];
        const r = a[j+1];
        if (next === l) { j--; continue; }
        if (next === r) { j++; continue; }
        if (a.indexOf(next) !== -1) return 'NO';

        if (j === a.length - 1) { j++; a.push(next); continue; }
        if (j === 0) { a.unshift(next); continue; }
        return 'NO'
    }
    let others = 'abcdefghijklmnopqrstuvwxyz';
    for (let i = 0; i < a.length; i++) others = others.replace(a[i], '');
    return 'YES\n' + a.join('') + others;
}
let t = +readline();
while(t--) print(problem(readline()))

process.stdin.resume()
process.stdin.setEncoding('utf-8')

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let ptr = 0
  let t = readInt(input, ptr++)
  // const alpha = "abcdefghijklmnopqrstuvwxyz"
  while(t--) {
    const s = input[ptr++]
    let ans = ''
    let l = s.length
    let map = new Array(26)
    for(let i = 0; i < 26; i++) {
      map[i] = [-1,-1]
    }
    let done = {}

    let curr = s.charCodeAt(0) - 97
    ans = s[0]
    done[curr] = true
    let f = true
    for(let i = 1; i < l && f; i++) {
      let char = s.charCodeAt(i) - 97
      if(map[curr][0] === char || map[curr][1] === char) {
        curr = char
      }
      else if(map[curr][0] === -1 && !done[char]) {
        map[curr][0] = char
        map[char][1] = curr
        curr = char
        done[char] = true
        ans = s[i] + ans
      }
      else if(map[curr][1] === -1 && !done[char]) {
        map[curr][1] = char
        map[char][0] = curr
        curr = char
        done[char] = true
        ans = ans + s[i]
      }
      else f = false
    }
    if(f) {
      wr('YES')
      for(let i = 0; i < 26; i++) {
        if(!done[i]) ans += String.fromCharCode(i + 97)
      }
      wr(ans)
    }
    else wr('NO')
    // wr(map)
  }
}

const alphabet = 'bacdefghijklmnopqrstuvwxyz'.split('')

const linkNode = (tree, keyA, keyB) => {
  const elA = tree[keyA]
  const elB = tree[keyB]
  const left = elA.left
  const right = elA.right
  if (left === keyB || right === keyB){
    return
  }
  const freeA = []
  if (!elA.left) {
    freeA.push('left')
  }
  if (!elA.right) {
    freeA.push('right')
  }
  if (freeA.length === 0) {
    throw new Error('overflow')
  }
  let usedProp = null

  for (const prop of freeA) {
    if (prop === 'left') {
      if (!elB.right) {
        usedProp = ['left', 'right']
      }
    } else {
      if (!elB.left) {
        usedProp = ['right', 'left']
      }
    }
  }

  if (!usedProp) {
    throw new Error('no link')
  }
  elA[usedProp[0]] = keyB
  elB[usedProp[1]] = keyA
}

const processData = (lines) => {
  const num = +lines[0]

  for (let j=0; j<num; j++){
    const pass = lines[j+1].split('')
    const tree = {}
    try {
      for (let i = 0; i < pass.length; i++) {
        const letter = pass[i]
        tree[letter] = tree[letter] || {}
        if (i > 0) {
          const prevLetter = pass[i - 1]
          tree[prevLetter] = tree[prevLetter] || {}
          linkNode(tree, letter, prevLetter)
        }
        if (i < pass.length - 1) {
          const nextLetter = pass[i + 1]
          tree[nextLetter] = tree[nextLetter] || {}
          linkNode(tree, letter, nextLetter)
        }
      }
      let result = ''
      const firstLetter = Object.keys(tree)[0]
      let mark = firstLetter
      let usedMap = {}
      let isOk = true
      // go to left
      while (mark) {
        if (usedMap[mark]) {
          isOk = false
          break;
        }
        result = mark + result
        usedMap[mark] = true
        if (tree[mark].left) {
          mark = tree[mark].left
        } else {
          mark = null
        }
      }

      if (tree[firstLetter].right) {
        mark = tree[firstLetter].right
      }

      // go to right
      while (isOk && mark) {
        if (usedMap[mark]) {
          isOk = false
          break;
        }
        result = result + mark
        usedMap[mark] = true
        if (tree[mark].right) {
          mark = tree[mark].right
        } else {
          mark = null
        }
      }

      if (isOk) {
        console.log('YES')
        for (const a of alphabet) {
          if (!usedMap[a]) {
            result += a
          }
        }
        console.log(result)
      } else {
        console.log('NO')
      }
    } catch(e) {
      console.log('NO')
    }
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

'use strict'

const problem = (s) => {
    if (s.length < 2) return 'YES\nabcdefghijklmnopqrstuvwxyz';
    if (s.length === 2) return s + 'abcdefghijklmnopqrstuvwxyz'.replace(s[0], '').replace(s[1], '')
    let a = [ s[0], s[1] ];
    let j = 1;
    for (let i = 2; i < s.length; i++) {
        const next = s[i];
        const l = a[j-1];
        const r = a[j+1];
        if (next === l) { j--; continue; }
        if (next === r) { j++; continue; }
        if (a.indexOf(next) !== -1) return 'NO';

        if (j === a.length - 1) { j++; a.push(next); continue; }
        if (j === 0) { a.unshift(next); continue; }
        return 'NO'
    }
    let others = 'abcdefghijklmnopqrstuvwxyz';
    for (let i = 0; i < a.length; i++) others = others.replace(a[i], '');
    return 'YES\n' + a.join('') + others;
}
let t = +readline();
while(t--) print(problem(readline()))

'use strict'

const problem = (s) => {
    if (s.length < 2) return 'YES\nabcdefghijklmnopqrstuvwxyz';
    if (s.length === 2) return s + 'abcdefghijklmnopqrstuvwxyz'.replace(s[0], '').replace(s[1], '')
    let a = [ s[0], s[1] ];
    let b = new Set(a);
    let j = 1;
    for (let i = 2; i < s.length; i++) {
        const next = s[i];
        const l = a[j-1];
        const r = a[j+1];
        if (next === l) { j--; continue; }
        if (next === r) { j++; continue; }
        if (b.has(next)) return 'NO';

        b.add(next);
        if (j === a.length - 1) { j++; a.push(next); continue; }
        if (j === 0) { a.unshift(next); continue; }
        return 'NO'
    }
    let others = 'abcdefghijklmnopqrstuvwxyz';
    for (let i of b) others = others.replace(i, '');
    return 'YES\n' + a.join('') + others;
}
let t = +readline();
while(t--) print(problem(readline()))

process.stdin.resume()
process.stdin.setEncoding('utf-8')

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let ptr = 0
  let t = readInt(input, ptr++)
  // const alpha = "abcdefghijklmnopqrstuvwxyz"
  while(t--) {
    const s = input[ptr++]
    let ans = ''
    let l = s.length
    let map = new Array(26)
    for(let i = 0; i < 26; i++) {
      map[i] = [-1,-1]
    }
    let done = {}

    let curr = s.charCodeAt(0) - 97
    ans = s[0]
    done[curr] = true
    let f = true
    for(let i = 1; i < l && f; i++) {
      let char = s.charCodeAt(i) - 97
      if(map[curr][0] === char || map[curr][1] === char) {
        curr = char
      }
      else if(map[curr][0] === -1 && !done[char]) {
        map[curr][0] = char
        map[char][1] = curr
        curr = char
        done[char] = true
        ans = s[i] + ans
      }
      else if(map[curr][1] === -1 && !done[char]) {
        map[curr][1] = char
        map[char][0] = curr
        curr = char
        done[char] = true
        ans = ans + s[i]
      }
      else f = false
    }
    if(f) {
      wr('YES')
      for(let i = 0; i < 26; i++) {
        if(!done[i]) ans += String.fromCharCode(i + 97)
      }
      wr(ans)
    }
    else wr('N0')
    // wr(map)
  }
}

const alphabet = 'bacdefghijklmnopqrstuvwxyz'.split('')

const linkNode = (tree, keyA, keyB) => {
  const elA = tree[keyA]
  const elB = tree[keyB]
  const left = elA.left
  const right = elA.right
  if (left === keyB || right === keyB){
    return
  }
  const freeA = []
  const freeB = []
  if (!elA.left) {
    freeA.push('left')
  }
  if (!elA.right) {
    freeA.push('right')
  }
  if (freeA.length === 0) {
    throw new Error('overflow')
  }
  let usedProp = null
  for (let prop in freeA) {
    if (prop === 'left') {
      if (!elB.right) {
        usedProp = ['left', 'right']
      }
    } else {
      if (!elB.left) {
        usedProp = ['right', 'left']
      }
    }
  }

  if (!usedProp) {
    throw new Error('no link')
  }
  elA[usedProp[0]] = keyB
  elB[usedProp[1]] = keyA
}

const processData = (lines) => {
  const num = +lines[0]

  for (let j=0; j<num; j++){
    const pass = lines[j+1].split('')
    const tree = {}
    try {
      for (let i = 0; i < pass.length; i++) {
        const letter = pass[i]
        tree[letter] = tree[letter] || {}
        if (i > 0) {
          const prevLetter = pass[i - 1]
          tree[prevLetter] = tree[prevLetter] || {}
          linkNode(tree, letter, prevLetter)
        }
        if (i < pass.length - 1) {
          const nextLetter = pass[i + 1]
          tree[nextLetter] = tree[nextLetter] || {}
          linkNode(tree, letter, nextLetter)
        }
      }
      let result = ''
      const firstLetter = Object.keys(tree)[0]
      let mark = firstLetter
      let usedMap = {}
      let isOk = true
      // go to left
      while (mark) {
        if (usedMap[mark]) {
          isOk = false
          break;
        }
        result = mark + result
        usedMap[mark] = true
        if (tree[mark].left) {
          mark = tree[mark].left
        } else {
          mark = null
        }
      }

      if (tree[firstLetter].right) {
        mark = tree[firstLetter].right
      }

      // go to right
      while (isOk && mark) {
        if (usedMap[mark]) {
          isOk = false
          break;
        }
        result = result + mark
        usedMap[mark] = true
        if (tree[mark].right) {
          mark = tree[mark].right
        } else {
          mark = null
        }
      }

      if (isOk) {
        console.log('YES')
        for (const a of alphabet) {
          if (!usedMap[a]) {
            result += a
          }
        }
        console.log(result)
      } else {
        console.log('NO')
      }
    } catch(e) {
      console.log('NO')
    }
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

const alphabet = 'bacdefghijklmnopqrstuvwxyz'.split('')

const linkNode = (tree, keyA, keyB) => {
  const elA = tree[keyA]
  const elB = tree[keyB]
  const left = elA.left
  const right = elA.right
  if (left === keyB || right === keyB){
    return
  }
  const freeA = []
  const freeB = []
  if (!elA.left) {
    freeA.push('left')
  }
  if (!elA.right) {
    freeA.push('right')
  }
  if (freeA.length === 0) {
    console.log(tree)
    console.log(keyA, keyB)
    throw new Error('overflow')
  }
  let usedProp = null
  for (let prop in freeA) {
    if (prop === 'left') {
      if (!elB.right) {
        usedProp = ['left', 'right']
      }
    } else {
      if (!elB.left) {
        usedProp = ['right', 'left']
      }
    }
  }

  if (!usedProp) {
    throw new Error('no link')
  }
  elA[usedProp[0]] = keyB
  elB[usedProp[1]] = keyA
}

const processData = (lines) => {
  const num = +lines[0]

  for (let j=0; j<num; j++){
    const pass = lines[j+1].split('')
    const tree = {}
    try {
      for (let i = 0; i < pass.length; i++) {
        const letter = pass[i]
        tree[letter] = tree[letter] || {}
        if (i > 0) {
          const prevLetter = pass[i - 1]
          tree[prevLetter] = tree[prevLetter] || {}
          linkNode(tree, letter, prevLetter)
        }
        if (i < pass.length - 1) {
          const nextLetter = pass[i + 1]
          tree[nextLetter] = tree[nextLetter] || {}
          linkNode(tree, letter, nextLetter)
        }
      }
      let result = ''
      const firstLetter = Object.keys(tree)[0]
      let mark = firstLetter
      let usedMap = {}
      let isOk = true
      // go to left
      while (mark) {
        if (usedMap[mark]) {
          isOk = false
          break;
        }
        result = mark + result
        usedMap[mark] = true
        if (tree[mark].left) {
          mark = tree[mark].left
        } else {
          mark = null
        }
      }

      if (tree[firstLetter].right) {
        mark = tree[firstLetter].right
      }

      // go to right
      while (isOk && mark) {
        if (usedMap[mark]) {
          isOk = false
          break;
        }
        result = result + mark
        usedMap[mark] = true
        if (tree[mark].right) {
          mark = tree[mark].right
        } else {
          mark = null
        }
      }

      if (isOk) {
        console.log('YES')
        for (const a of alphabet) {
          if (!usedMap[a]) {
            result += a
          }
        }
        console.log(result)
      } else {
        console.log('NO')
      }
    } catch(e) {
      console.error(e)
      console.log('NO')
    }
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})


Theofanis started playing the new online game called "Among them". However, he always plays with Cypriot players, and they all have the same name: "Andreas" (the most common name in Cyprus).In each game, Theofanis plays with $$$n$$$ other players. Since they all have the same name, they are numbered from $$$1$$$ to $$$n$$$.The players write $$$m$$$ comments in the chat. A comment has the structure of "$$$i$$$ $$$j$$$ $$$c$$$" where $$$i$$$ and $$$j$$$ are two distinct integers and $$$c$$$ is a string ($$$1 \le i, j \le n$$$; $$$i \neq j$$$; $$$c$$$ is either imposter or crewmate). The comment means that player $$$i$$$ said that player $$$j$$$ has the role $$$c$$$.An imposter always lies, and a crewmate always tells the truth. Help Theofanis find the maximum possible number of imposters among all the other Cypriot players, or determine that the comments contradict each other (see the notes for further explanation).Note that each player has exactly one role: either imposter or crewmate.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of each test case follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 5 \cdot 10^5$$$) — the number of players except Theofanis and the number of comments. Each of the next $$$m$$$ lines contains a comment made by the players of the structure "$$$i$$$ $$$j$$$ $$$c$$$" where $$$i$$$ and $$$j$$$ are two distinct integers and $$$c$$$ is a string ($$$1 \le i, j \le n$$$; $$$i \neq j$$$; $$$c$$$ is either imposter or crewmate). There can be multiple comments for the same pair of $$$(i, j)$$$. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ and the sum of all $$$m$$$ does not exceed $$$5 \cdot 10^5$$$.

For each test case, print one integer — the maximum possible number of imposters. If the comments contradict each other, print $$$-1$$$.

5
3 2
1 2 imposter
2 3 crewmate
5 4
1 3 crewmate
2 5 crewmate
2 4 imposter
3 4 imposter
2 2
1 2 imposter
2 1 crewmate
3 5
1 2 imposter
1 2 imposter
3 2 crewmate
3 2 crewmate
1 3 imposter
5 0

NoteIn the first test case, imposters can be Andreas $$$2$$$ and $$$3$$$.In the second test case, imposters can be Andreas $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$.In the third test case, comments contradict each other. This is because player $$$1$$$ says that player $$$2$$$ is an imposter, and player $$$2$$$ says that player $$$1$$$ is a crewmate. If player $$$1$$$ is a crewmate, then he must be telling the truth, so player $$$2$$$ must be an imposter. But if player $$$2$$$ is an imposter then he must be lying, so player $$$1$$$ can't be a crewmate. Contradiction.

'use strict';

function solve(n, m, a) {
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        w = [];
  let idx = 0;
  const add = (i, j, c) => {
    e[idx] = j, ne[idx] = h[i], w[idx] = c, h[i] = idx++;
  };
  for (let [x, y, z] of a) {
    const i = Number(x) - 1,
          j = Number(y) - 1;
    if (z === 'imposter') {
      add(i, j, 1);
      add(j, i, 1);
    } else {
      add(i, j, 0);
      add(j, i, 0);
    }
  }
  const vis = [];
  const nums = new Array(n);
  const check = i => {
    const query = [i];
    nums[i] = 0;
    for (let i of query) {
      vis[i] = 1;
      for (let k = h[i]; k !== -1; k = ne[k]) {
        const j = e[k];
        if (nums[j] !== undefined && nums[j] !== (nums[i] ^ w[k])) return -1;
        if (vis[j]) continue;
        vis[j] = 1;
        nums[j] = nums[i] ^ w[k];
        query.push(j);
      }
    }
    let res = 0;
    for (let i of query) res += nums[i];
    return Math.max(res, query.length - res);
  };
  let res = 0;
  for (let i = 0; i < n; i++) {
    if (vis[i]) continue;
    const ans = check(i);
    if (ans === -1) return -1;
    res += ans;
  }
  return res;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = [];
      let tmp = m;
      while (tmp--) {
        a.push((await read()).split(' '));
      }
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, m] = lines[l++].trim().split(' ').map(Number)
        const says = lines.slice(l, l + m).map(str => str.trim().split(' ').map((x, i) => i < 2 ? +x : x))
        l += m
        console.log(solve(n, m, says))
    }
// })()
})

function solve(n, m, says) {
    const vs = Array(n + 1).fill(-1)
    const adj = {}
    says.forEach(([a, b, s]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        const w = s === 'crewmate' // same or not
        adj[a].push([b, w])
        adj[b].push([a, w])
    })

    let c0 = 0
    let c1 = 0
    const visited = {}
    for (let i = 1; i <= n; i++) {
        if (!visited[i]) {
            const r = dfs(adj, i, visited, vs)
            if (!r) return -1

            const [a, b] = r
            c0 += Math.max(a, b)
            c1 += Math.min(a, b)
        }
    }

    return c0 + (n - c0 - c1)
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1, 1]]
    let c0 = 0
    let c1 = 0
    const cache = []
    while (stack.length) {
        const [u, i, p, color] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            cache[u] = color
            if (color === 0) c0++
            if (color === 1) c1++
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const [v, w] = nb[i]
            if (!visited[v]) { // has circle
                stack.push([v, 0, u, w ? color : (1 ^ color)])
            } else {
                if (w && cache[u] !== cache[v]) return null
                if (!w && cache[u] !== (1 ^ cache[v])) return null
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return [c0, c1]
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, m] = lines[l++].trim().split(' ').map(Number)
        const says = lines.slice(l, l + m).map(str => str.trim().split(' ').map((x, i) => i < 2 ? +x : x))
        l += m
        console.log(solve(n, m, says))
    }
// })()
})

function solve(n, m, says) {
    const vs = Array(n + 1).fill(-1)
    const adj = {}
    const not = says.some(([a, b, s]) => {
        if (vs[a] < 0 && vs[b] < 0) {
            vs[a] = 1
            vs[b] = s === 'crewmate' ? 1 : 0
        } else if (vs[b] < 0) {
            vs[b] = s === 'crewmate' ? vs[a] : (vs[a] ^ 1)
        } else if (vs[a] < 0) {
            vs[a] = s === 'crewmate' ? vs[b] : (vs[b] ^ 1)
        } else {
            if (s === 'crewmate' && vs[a] !== vs[b]) return true
            if (s === 'imposter' && vs[a] === vs[b]) return true
        }
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    if (not) return -1

    let c0 = 0
    let c1 = 0
    const visited = {}
    for (let i = 1; i <= n; i++) {
        if (!visited[i]) {
            const [a, b] = dfs(adj, i, visited, vs)
            c0 += Math.max(a, b)
            c1 += Math.min(a, b)
        }
    }

    return c0 + (n - c0 - c1)
}
function dfs(adj, r, visited, vs) {
    const stack = [[r, 0, -1]]
    let c0 = 0
    let c1 = 0
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            if (vs[u] === 0) c0++
            if (vs[u] === 1) c1++
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p && !visited[v]) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return [c0, c1]
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, m] = lines[l++].trim().split(' ').map(Number)
        const says = lines.slice(l, l + m).map(str => str.trim().split(' ').map((x, i) => i < 2 ? +x : x))
        l += m
        console.log(solve(n, m, says))
    }
// })()
})

function solve(n, m, says) {
    const vs = Array(n + 1).fill(-1)
    // const adj = {}
    const not = says.some(([a, b, s]) => {
        if (vs[a] < 0 && vs[b] < 0) {
            vs[a] = 1
            vs[b] = s === 'crewmate' ? 1 : 0
        } else if (vs[b] < 0) {
            vs[b] = s === 'crewmate' ? vs[a] : (vs[a] ^ 1)
        } else if (vs[a] < 0) {
            vs[a] = s === 'crewmate' ? vs[b] : (vs[b] ^ 1)
        } else {
            if (s === 'crewmate' && vs[a] !== vs[b]) return true
            if (s === 'imposter' && vs[a] === vs[b]) return true
        }
        // adj[a] = adj[a] || []
        // adj[b] = adj[b] || []
        // adj[a].push(b)
        // adj[b].push(a)
    })
    if (not) return -1

    let c0 = 0
    let c1 = 0
    for (let i = 1; i <= n; i++) {
        if (vs[i] === 0) c0++
        if (vs[i] === 1) c1++
    }
    return Math.max(c0, c1) + (n - c0 - c1)
}


Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?

The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.

Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.

'use strict'

let lll

const N = +readline()

const rs = []

while (lll = readline()) {
  const rr = lll.split(' ').map(v => parseInt(v))
  if (!rs[rr[0]]) rs[rr[0]] = {rr: []}
  rs[rr[0]][rr[1]] = rr[2]
  rs[rr[0]].rr.push(rr[1])
  if (!rs[rr[1]]) rs[rr[1]] = {rr: []}
  rs[rr[1]][rr[0]] = 0
  rs[rr[1]].rr.push(rr[0])
}

const next = (f, t) => {
  const ws = rs[t].rr
  const n = ws[0] == f ? ws[1] : ws[0]
  const p = rs[t][n]
  return [n, p]
}

let r1 = 1
let r2 = rs[1].rr[0]
let p1 = rs[1][r2]

while (r2 != 1) {
  const w = next(r1, r2)
  const rn = w[0]
  r1 = r2
  r2 = rn
  p1 += w[1]
}

r1 = 1
r2 = rs[1].rr[1]
let p2 = rs[1][r2]

while (r2 != 1) {
  const w = next(r1, r2)
  const rn = w[0]
  r1 = r2
  r2 = rn
  p2 += w[1]
}

print(Math.min(p1, p2))

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var matrix = [], indicator = 0, N;
/**
 * while(true){
 *  string  input = Console.ReadLine();
 * }
 */
/**
 *
 *
  6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42

 */
var findNextPath = function (matrix, N, path, index) {
    for (let i = 0; i < N; i++) {
        if (matrix[index][i] != 0 && !path.includes(i) ||
            matrix[i][index] != 0 && !path.includes(i))
            return i;
    }
    return -1;
}

rl.on('line', (input) => {

    if (indicator == 0) {
        N = parseInt(input);
        indicator++;
        matrix = new Array(N).fill(0).map(() => new Array(N).fill(0));
        //console.log(matrix);
    }
    else {
        let temp = input.split(' ').map(item => parseInt(item));
        let a = temp[0], b = temp[1], price = temp[2];
        //console.log("a=%d  b=%d  price=%d",a,b,price);
        matrix[a - 1][b - 1] = price;

    }

}).on('close', () => {
    /**
     *
     * path{0,4,2,1,3,5}
     */
    //console.log(matrix);
    let path = [0];
    let nIndex = findNextPath(matrix, N, path, 0);

    while (nIndex != -1) {
        path.push(nIndex);
        nIndex = findNextPath(matrix, N, path, nIndex);
    }
    let CW = matrix[path[N - 1]][0];
    let ACW = matrix[0][path[N - 1]];

    for (let i = 0, j = N - 1; i < N - 1; i++, j--) {
        CW += matrix[path[i]][path[i + 1]];
        ACW += matrix[path[j]][path[j - 1]];
    }
    console.log((ACW > CW) ? CW : ACW);
});

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

function main() {
  const n = parseInt(readline());
  const roads = new Map();
  let neighbours = (new Array(n+1)).fill(new Array());
  let start = 0,
      curr = 0,
      next = 0,
      d1 = 0,
      d2 = 0;
  for (let i=0; i<n; i++) {
    const [a, b, c] = readline().split(" ").map(x => parseInt(x));
    roads.set(a+"-"+b, c);
    neighbours[a] = neighbours[a].concat(b);
    neighbours[b] = neighbours[b].concat(a);
    if (start == 0) {
      start = a;
      curr = a;
      next = b;
    }
  }

  do {
    if (roads.has(curr+"-"+next)) {
      d1 += roads.get(curr+"-"+next);
    } else {
      d2 += roads.get(next+"-"+curr);
    }
    if (neighbours[next][0] == curr) {
      curr = next;
      next = neighbours[next][1];
    } else {
      curr = next;
      next = neighbours[next][0];
    }
  } while(curr != start);

  console.log(Math.min(d1,d2));
}