const fs = require('fs');
const readline = require('readline');
const path = require('path')

class PacketsCounter {
    count = undefined

    isInited() {
        return typeof this.count !== 'undefined';
    }

    setInitialCount(count) {
        if (this.isInited()) {
            throw new Error('Commands counter is already inited');
        }

        this.count = count;
    }

    isPacketsLeft() {
        return this.count > 0;
    }

    decreaseCounter() {
        this.count--;
    }
}

class MonitorsMatcher {
    list = [] // all monitors

    addMonitor(monitor) {
        const [w, h] = monitor.split(' ');

        this.list.push({ w, h });
    }

    countCombinations() {
        let sum = 0;

        for (let i = 0; i < this.list.length; i++) {
            const first = this.list[i];

            for (let j = i + 1; j < this.list.length; j++) {
                const second = this.list[j];

                if (first.h === second.h || first.w === second.h || first.h === second.w || first.w === second.w) {
                    sum += 1
                }
            }
        }

        return sum;
    }
}

// MAIN

function main() {
    const monitorsMatcher = new MonitorsMatcher();
    const commandsCounter = new PacketsCounter();
    // const readStream = fs.createReadStream(path.resolve(__dirname, './input'));
    const readStream = process.stdin;

    const lineCallback = (line) => processLine(monitorsMatcher, commandsCounter, line);
    const closeCallback = () => sendAnswer(String(monitorsMatcher.countCombinations()));

    initInputRead(readStream, lineCallback, closeCallback);
}

main();

// ---

function initInputRead(inputInterface, lineCb, closeCb) {
    const readInterface = readline.createInterface({
        input: inputInterface,
    });

    readInterface.on('line', line => lineCb(line));
    readInterface.on('close', () => closeCb());
}

function processLine(monitorsMatcher, commandsCounter, line) {
    // first line: init counter
    if (!commandsCounter.isInited()) {
        commandsCounter.setInitialCount(Number(line));
        return;
    }

    // exec commands while counter of commands is more than inited in first line
    if (commandsCounter.isPacketsLeft()) {
        monitorsMatcher.addMonitor(line);
        commandsCounter.decreaseCounter();
        return;
    }
}

function sendAnswer(answer) {
    process.stdout.write(answer);
    process.stdout.write('\n');
}

const readline = require('readline');
const fs = require('fs');

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

let count = 0;
let n = 0;
let solo = [];
let pairs = [];
let values = [];

function calcEqual(a) {
    let last = -1;
    let res = 0;
    let cnt = 0;
    a.sort();
    for (let i = 0; i < a.length; i++) {
        let x = a[i];
        if (JSON.stringify(x) === JSON.stringify(last)) {
            res += cnt;
            cnt += 1;
        } else {
            cnt = 1;
        }
        last = x;
    }
    return res;
}

readInterface.on('line', function(line) {
    if (count === 0) {
        n = +line;
    } else {
        let pair = line.split(' ').map(el => { return +el; });
        w = pair[0];
        h = pair[1];
        solo.push(w);
        if (h != w) {
            solo.push(h);
            pairs.push([Math.min.apply(null, pair), Math.max.apply(null, pair)]);
        }
    }
    if (count === n) {
        console.log(calcEqual(solo) - calcEqual(pairs));
    }

    count++;
});

const nextString = (function() {
  const listeners = [], strings = [], ps = process.stdin
  let last = ''
  ps.setEncoding('utf8')
  ps.on('readable', () => {
    let chunk
    while ((chunk = ps.read()) !== null) {
      chunk = (last + chunk).split(/\r\n|\r|\n/)
      last = chunk[chunk.length - 1]
      for (let i = 0; i < chunk.length - 1; ++i) {
        if (chunk[i].length > 0) {
          if (listeners.length > 0) {
            listeners.shift(1)(chunk[i])
          }
          else {
            strings.push(chunk[i])
          }
        }
      }
    }
  })
  const fn = resolve => {
    if (strings.length > 0) {
      resolve(strings.shift(1))
    }
    else {
      listeners.push(resolve)
    }
  }
  return () => new Promise(fn)
})()

async function main() {
  let n = +await nextString()
  let obj = {}
  let ans = 0
  for (let i = 0; i < n; ++i) {
    let [a, b] = (await nextString()).split(' ').map(x => +x).sort((a, b) => a - b)
    let mid = a + '_' + b
    if (a !== b) {
      ans += (obj[a] || 0) + (obj[b] || 0) - (obj[mid] || 0)
    }
    else {
      ans += (obj[a] || 0)
    }
    // console.log('i = ' + i + ': ' + ans)
    obj[a] = obj[a] ? obj[a] + 1 : 1
    if (a !== b) {
      obj[b] = obj[b] ? obj[b] + 1 : 1
    }
    obj[mid] = obj[mid] ? obj[mid] + 1 : 1
  }
  console.log(ans)
}

main()

let _DEBUG;

const fs = require('fs');
const print = console.log;
const debug = (x) => {
  if (!_DEBUG) return;
  let vn = Object.keys(x)[0];
  console.error(`${vn}: ${x[vn]}`);
};
const debugf = !_DEBUG ? () => {} : console.error;

let input = fs.readFileSync(0).toString();
input = input.split(/\r?\n/g);

let n = +input[0];

let s = new Map();
let hw = new Map();

let res = 0n;

for (let i = 0; i < n; i++) {
  let row = input[i + 1].split(' ').map((x) => +x);
  let [x, y] = row;

  // x <= y
  if (x > y) {
    [x, y] = [y, x];
  }

  let a = s.get(x) || 0;
  let b = s.get(y) || 0;
  let ab = (hw.has(x) && hw.get(x).get(y)) || 0;
  if (x == y) {
    res += BigInt(a);
  } else {
    res += BigInt(a + b - ab);
  }

  debugf(`${x} ${y} -> ${a} ${b}  ${ab}`);
  debug({ res });

  s.set(x, (s.get(x) || 0) + 1);
  if (x != y) {
    s.set(y, (s.get(y) || 0) + 1);
  }

  if (!hw.has(x)) {
    hw.set(x, new Map());
  }
  let hw2 = hw.get(x);
  hw2.set(y, (hw2.get(y) || 0) + 1);

  debugf(`??? ${x} -> ${s.get(x)}`);
}

print(`${res}`);

const readline = require('readline');
const fs = require('fs');

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

let count = 0;
let total = 0;
let values = [];
let output = 0;

readInterface.on('line', function(line) {
    if (count === 0) {
        total = +line;
    } else {
        values.push(line);
    }

    if (values.length === total) {

        for (let i = 0; i < total; i++) {
            let item = values.shift();

            let filtered = values.filter(el => {
                let itemSize = item.split(' ');
                let itemW = itemSize[0];
                let itemH = itemSize[1];

                let elSize = el.split(' ');
                let elW = elSize[0];
                let elH = elSize[1];
                return itemH === elH || itemW === elH || itemW === elW || itemH === elW;
            })

            output += filtered.length;
        }

        console.log(output);
    }

    count++;
});

var readline = require('readline');

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

var count_of_monitors
var monitors_sizes = []
function start() {
    rl.question("", function(answer) {
        count_of_monitors = parseInt(answer)
        get_mon()
    });
}

function get_monitors() {
    rl.question("", function(answer) {
        monitors_sizes.push(answer)
        count_of_monitors--
        get_mon()
    });

}

function get_mon() {
    if (count_of_monitors > 0) {
        get_monitors()
    } else {
        get_pairs()
    }
}

function factorial(n) {
  return (n != 1) ? n * factorial(n - 1) : 1;
}

function get_pairs() {

    var pairs = []
    var dubl_pairs = 0
    var count = 0

    monitors_sizes = monitors_sizes.sort()

    for (var i = 0; i < monitors_sizes.length; i++) {
        if (i >= 0) {
            if (monitors_sizes[i] != monitors_sizes[i - 1]) {
                count = 0
                monitors_sizes.slice(i + 1).filter((size, index) => {
                    var i_str = monitors_sizes[i].split(" ")
                    var index_str = size.split(" ")
                    if (parseInt(i_str[0]) == parseInt(index_str[0]) ||
                        parseInt(i_str[0]) == parseInt(index_str[1]) ||
                        parseInt(i_str[1]) == parseInt(index_str[0]) ||
                        parseInt(i_str[1]) == parseInt(index_str[1])) {
                            pairs.push(`${i_str} - ${index_str}`)
                            count++
                            return true
                        }
                })
            } else {
                count--
                dubl_pairs += count
            }
        }

    }
    console.log(pairs.length + dubl_pairs)

}

start();

let i = '';
process.stdin.on('data', (c) => (i += c));
process.stdin.on('end', () => {
  const { EOL } = require('os');
  const lines = i.split(EOL);
  const params = [];

  for (let i = 1; i < lines.length; i++) {
    params.push(lines[i].split(' ').map((x) => parseInt(x)));
  }

  const recurse = (arr, sum = 0) => {
    if (arr.length < 1) {
      return sum;
    } else {
      const x = arr[arr.length - 1][0];
      const y = arr[arr.length - 1][1];
      for (let i = 0; i < arr.length - 1; i++) {
        if (
          x === params[i][0] ||
          x === params[i][1] ||
          y === params[i][0] ||
          y === params[i][1]
        ) {
          sum++;
        }
      }
      arr.pop();
      return recurse(arr, sum);
    }
  };

  console.log(recurse(params, 0));
});

let i = '';
process.stdin.on('data', (c) => (i += c));
process.stdin.on('end', () => {
  const { EOL } = require('os');
  const lines = i.split(EOL);
  const params = [];
  let resSum = 0;

  for (let i = 1; i < lines.length; i++) {
    params.push(lines[i].split(' ').map((x) => parseInt(x)));
  }

  for (let i = 0; i < params.length - 1; i++) {
    for (let j = i + 1; j < params.length; j++) {
      if (
        params[i][0] === params[j][0] ||
        params[i][0] === params[j][1] ||
        params[i][1] === params[j][0] ||
        params[i][1] === params[j][1]
      ) {
        resSum++;
      }
    }
  }

  console.log(resSum);
});

function program(lines) {

  const count = Number(lines[0]);
  const heights = new Map();
  const results = new Set();

  for (let i = 1; i <= count; i++) {

    const [wS, hS] = lines[i].trim().split(' ');

    const w = Number(wS.trim());
    if (!heights.has(w)) {
      heights.set(w, new Set());
    }

    const wSet = heights.get(w);
    if (!wSet.has(i)) {
      for (const el of wSet) {
        results.add(`${i}-${el}`);
      }
      wSet.add(i);
    }

    const h = Number(hS.trim());
    if (!heights.has(h)) {
      heights.set(h, new Set());
    }
    const hSet = heights.get(h);
    if (!hSet.has(i)) {
      for (const el of hSet) {
        results.add(`${i}-${el}`);
      }
      hSet.add(i);
    }
  }

  return results.size;
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  const lines = i.split(EOL)
  console.log(program(lines));
})

function program(lines) {

  const count = Number(lines[0]);
  const heights = new Map();

  for (let i = 1; i <= count; i++) {

    const [wS, hS] = lines[i].trim().split(' ');

    const w = Number(wS.trim());
    if (!heights.has(w)) {
      heights.set(w, new Set());
    }
    heights.get(w).add(i);

    const h = Number(hS.trim());
    if (!heights.has(h)) {
      heights.set(h, new Set());
    }
    heights.get(h).add(i);
  }

  const results = new Set();

  for (const items of heights.values()) {
    for (const first of items) {
      for (const second of items) {
        if (first !== second) {
          results.add(`${first}-${second}`);
        }
      }
    }
  }

  return results.size / 2;
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  const lines = i.split(EOL)
  console.log(program(lines));
})

const readline = require('readline');

const data = [];
let length = 0;
let msgCounter = 0;
let pairsCounter = 0;

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

function countPairs () {
  for (let i = data.length - 1; i > 0; i--) {
    for (let j = i - 1; j >= 0; j--) {
      if (data[i][0] === data[j][0]
        || data[i][0] === data[j][1]
        || data[i][1] === data[j][1]
        || data[i][1] === data[j][0]) {
          pairsCounter++;
      }
    }
  }
}

rl.on('line', input => {
  if (length === 0) length = +(input);
  else data.push(input.split(' '));

  if (length === msgCounter) {
    countPairs();
    console.log(pairsCounter);
    rl.close();
  } else msgCounter++;
});

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});

let content = []
let i = 0

function B (content) {
    let count = 0;
    for (let current = 0; current < content.length; current++) {
        let [h, w] = content[current]
        for (let next = current + 1; next < content.length; next++) {
            let val = content[next]
            if (val[0] === h || val[0] === w || val[1] === h || val[1] === w) {
                count++
            }
        }
    }
    console.log(count)
}

rl
    .on('line', value => {
        if (i === 0) {
            i++
            return
        }
        content.push(value.split(' '))
    })
    .on('close', () => {
        B(content)
    })

module.exports = B

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    let lines = i.split(EOL);
    const itemsLength = lines[0];
    lines = lines.slice(1, lines.length - 1);
    /****** */
    const monitors = [];
    lines.forEach(item => {
      monitors.push({
        width: item.split(' ')[0],
        height: item.split(' ')[1]
      })
    })
    let acceptableMonitorsCount = 0;
    function checkMonitors(m1, m2) {
      let accept = false;
      if ( m1.height === m2.height
        || m1.width === m2.height
        || m1.height === m2.width
        || m1.width === m2.width ) {
        accept = true;
      }
      return accept;
    }
    for (let i = 0; i < itemsLength - 1; i++) {
      for (let j = i + 1; j < itemsLength; j++) {
        if (checkMonitors(monitors[i], monitors[j])) {
          acceptableMonitorsCount++;
        }
      }
    }

    /****** */
    console.log(acceptableMonitorsCount);
});

var n = readline();
var pairs = []
var pairsCount = 0
var r = 0

for (var i = 0; i < n; i++) {
	var l = readline().split(' ')

	r += pairs.filter(el => el.includes(l[0]) || el.includes(l[1])).length;

	pairs.push(l)
}

print(r);

const readline = require('readline');
const fs = require('fs');

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

let count = 0;
let total = 0;
let values = [];
let output = 0;
let repeats = {};

readInterface.on('line', function(line) {
    if (count === 0) {
        total = +line;
    } else {
        if (values.includes(line)) {
            repeats[line] += 1;
        } else {
            repeats[line] = 1;
            values.push(line);
        }
    }

    if (values.length === total) {

        for (let i = 0; i < total; i++) {
            let item = values.shift();

            let filtered = values.filter(el => {
                let itemSize = item.split(' ');
                let itemW = itemSize[0];
                let itemH = itemSize[1];

                let elSize = el.split(' ');
                let elW = elSize[0];
                let elH = elSize[1];
                return itemH === elH || itemW === elH || itemW === elW || itemH === elW;
            })

            let result = filtered.length * repeats[item];

            output += filtered.length;
        }

        console.log(output);
    }

    count++;
});

const nextString = (function() {
  const listeners = [], strings = [], ps = process.stdin
  let last = ''
  ps.setEncoding('utf8')
  ps.on('readable', () => {
    let chunk
    while ((chunk = ps.read()) !== null) {
      chunk = (last + chunk).split(/\r\n|\r|\n/)
      last = chunk[chunk.length - 1]
      for (let i = 0; i < chunk.length - 1; ++i) {
        if (chunk[i].length > 0) {
          if (listeners.length > 0) {
            listeners.shift(1)(chunk[i])
          }
          else {
            strings.push(chunk[i])
          }
        }
      }
    }
  })
  const fn = resolve => {
    if (strings.length > 0) {
      resolve(strings.shift(1))
    }
    else {
      listeners.push(resolve)
    }
  }
  return () => new Promise(fn)
})()

async function main() {
  let n = +await nextString()
  let obj = {}
  let ans = 0
  for (let i = 0; i < n; ++i) {
    let [a, b] = (await nextString()).split(' ').map(x => +x).sort((a, b) => a - b)
    let mid = a + '_' + b
    if (a !== b) {
      ans += (obj[a] || 0) + (obj[b] || 0) - (obj[mid] || 0)
    }
    else {
      ans += (obj[a] || 0)
    }
    obj[a] = obj[a] ? obj[a] + 1 : 1
    obj[b] = obj[b] ? obj[b] + 1 : 1
    obj[mid] = obj[mid] ? obj[mid] + 1 : 1
  }
  console.log(ans)
}

main()

const nextString = (function() {
  const listeners = [], strings = [], ps = process.stdin
  let last = ''
  ps.setEncoding('utf8')
  ps.on('readable', () => {
    let chunk
    while ((chunk = ps.read()) !== null) {
      chunk = (last + chunk).split(/\r\n|\r|\n/)
      last = chunk[chunk.length - 1]
      for (let i = 0; i < chunk.length - 1; ++i) {
        if (chunk[i].length > 0) {
          if (listeners.length > 0) {
            listeners.shift(1)(chunk[i])
          }
          else {
            strings.push(chunk[i])
          }
        }
      }
    }
  })
  const fn = resolve => {
    if (strings.length > 0) {
      resolve(strings.shift(1))
    }
    else {
      listeners.push(resolve)
    }
  }
  return () => new Promise(fn)
})()

async function main() {
  let n = +await nextString()
  let obj = {}
  let ans = 0
  for (let i = 0; i < n; ++i) {
    let [a, b] = (await nextString()).split(' ').map(x => +x).sort((a, b) => a - b)
    let mid = a + '_' + b
    if (a !== b) {
      ans += (obj[a] || 0) + (obj[b] || 0) - (obj[mid] || 0)
    }
    else {
      ans += obj[a]
    }
    obj[a] = obj[a] ? obj[a] + 1 : 1
    obj[b] = obj[b] ? obj[b] + 1 : 1
    obj[mid] = obj[mid] ? obj[mid] + 1 : 1
  }
  console.log(ans)
}

main()

const nextString = (function() {
  const listeners = [], strings = [], ps = process.stdin
  let last = ''
  ps.setEncoding('utf8')
  ps.on('readable', () => {
    let chunk
    while ((chunk = ps.read()) !== null) {
      chunk = (last + chunk).split(/\r\n|\r|\n/)
      last = chunk[chunk.length - 1]
      for (let i = 0; i < chunk.length - 1; ++i) {
        if (chunk[i].length > 0) {
          if (listeners.length > 0) {
            listeners.shift(1)(chunk[i])
          }
          else {
            strings.push(chunk[i])
          }
        }
      }
    }
  })
  const fn = resolve => {
    if (strings.length > 0) {
      resolve(strings.shift(1))
    }
    else {
      listeners.push(resolve)
    }
  }
  return () => new Promise(fn)
})()

async function main() {
  let n = +await nextString()
  let obj = {}
  let ans = 0
  for (let i = 0; i < n; ++i) {
    let [a, b] = (await nextString()).split(' ').map(x => +x).sort((a, b) => a - b)
    let mid = a + '_' + b
    ans += (obj[a] || 0) + (obj[b] || 0) - (obj[mid] || 0)
    obj[a] = obj[a] ? obj[a] + 1 : 1
    obj[b] = obj[b] ? obj[b] + 1 : 1
    obj[mid] = obj[mid] ? obj[mid] + 1 : 1
  }
  console.log(ans)
}

main()

const nextString = (function() {
  const listeners = [], strings = [], ps = process.stdin
  let last = ''
  ps.setEncoding('utf8')
  ps.on('readable', () => {
    let chunk
    while ((chunk = ps.read()) !== null) {
      chunk = (last + chunk).split(/\r\n|\r|\n/)
      last = chunk[chunk.length - 1]
      for (let i = 0; i < chunk.length - 1; ++i) {
        if (chunk[i].length > 0) {
          if (listeners.length > 0) {
            listeners.shift(1)(chunk[i])
          }
          else {
            strings.push(chunk[i])
          }
        }
      }
    }
  })
  const fn = resolve => {
    if (strings.length > 0) {
      resolve(strings.shift(1))
    }
    else {
      listeners.push(resolve)
    }
  }
  return () => new Promise(fn)
})()

async function main() {
  let n = +await nextString()
  let obj = {}
  let ans = 0
  for (let i = 0; i < n; ++i) {
    let [a, b] = (await nextString()).split(' ').map(x => +x).sort((a, b) => a - b)
    let mid = a + '_' + b
    ans += obj[a] + obj[b] - obj[mid]
    obj[a] = obj[a] ? obj[a] + 1 : 1
    obj[b] = obj[b] ? obj[b] + 1 : 1
    obj[mid] = obj[mid] ? obj[mid] + 1 : 1
  }
  console.log(ans)
}

main()

const readline = require('readline');
const fs = require('fs');

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

let count = 0;
let n = 0;
let solo = [];
let pairs = [];
let values = [];

function calcEqual(a) {
    let last = -1;
    let res = 0;
    let cnt = 0;
    a.sort();
    for (let i = 0; i < a.length; i++) {
        let x = a[i];
        if (JSON.stringify(x) === JSON.stringify(last)) {
            res += cnt;
            cnt += 1;
        } else {
            cnt = 1;
        }
        last = x;
    }
    return res;
}

readInterface.on('line', function(line) {
    if (count === 0) {
        n = +line;
    } else {
        values.push(line);
    }

    if (values.length === n) {
        for (let i = 0; i < n; i++) {
            let pair = line.split(' ').map(el => { return +el; });
            w = pair[0];
            h = pair[1];
            solo.push(w);
            if (h != w) {
                solo.push(h);
                pairs.push([Math.min.apply(null, pair), Math.max.apply(null, pair)]);
            }
        }
        console.log(calcEqual(solo) - calcEqual(pairs));
    }

    count++;
});

const readline = require('readline');
const fs = require('fs');

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

let count = 0;
let total = 0;
let values = [];
let output = 0;

readInterface.on('line', function(line) {
    if (count === 0) {
        total = +line;
    } else {
        values.push(line);
    }

    if (values.length === total) {

        for (let i = 0; i < total; i++) {
            let item = values.shift();
            console.log('item', item);
            console.log('values', values);

            let filtered = values.filter(el => {
                let itemSize = item.split(' ');
                let itemW = itemSize[0];
                let itemH = itemSize[1];

                let elSize = el.split(' ');
                let elW = elSize[0];
                let elH = elSize[1];
                return itemH === elH || itemW === elH || itemW === elW || itemH === elW;
            })
            console.log('filtered', filtered);

            output += filtered.length;
        }

        console.log(output);
    }

    count++;
});

const readline = require('readline');
const fs = require('fs');

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

let count = 0;
let total = 0;
let values = [];
let output = 0;

readInterface.on('line', function(line) {
    if (count === 0) {
        total = +line;
    } else {
        values.push(line);
    }

    if (values.length === total) {

        for (let i = 0; i < total; i++) {
            let item = values.shift();

            let filtered = values.filter(el => {
                let itemSize = item.split(' ');
                let itemW = itemSize[0];
                let itemH = itemSize[1];

                let elSize = el.split(' ');
                let elW = elSize[0];
                let elH = elSize[1];
                return itemH === elH || itemW === elH || itemW === elW;
            })

            output += filtered.length;
        }

        console.log(output);
    }

    count++;
});

var readline = require('readline');

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

var count_of_monitors
var monitors_sizes = []
function start() {
    rl.question("", function(answer) {
        count_of_monitors = parseInt(answer)
        get_mon()
    });
}

function get_monitors() {
    rl.question("", function(answer) {
        monitors_sizes.push(answer)
        count_of_monitors--
        get_mon()
    });

}

function get_mon() {
    if (count_of_monitors > 0) {
        get_monitors()
    } else {
        get_pairs()
    }
}

function factorial(n) {
  return (n != 1) ? n * factorial(n - 1) : 1;
}

function get_pairs() {
    var pairs = []
    var count_factorial_combinations = 0
    var deleted_sizes = []
    var old_arr = monitors_sizes
    for (var i = 0; i < monitors_sizes.length; i++) {
        var fact_arr = monitors_sizes.filter(size => size == monitors_sizes[i])
        if (fact_arr.length > 1) {
            count_factorial_combinations += factorial(fact_arr.length)
            monitors_sizes = monitors_sizes.filter((word, index) => {

                if (word == monitors_sizes[i]) {
                    if (index == i) {
                        return true
                    } else {
                        deleted_sizes.push(monitors_sizes[i])
                        return false
                    }
                } else {
                    return true
                }
            })
        }
    }
    for (var first_mon_index = 0; first_mon_index < monitors_sizes.length; first_mon_index++) {
        if (typeof(monitors_sizes[first_mon_index + 1]) != "undefined") {
            for (var second_mon_index = first_mon_index + 1; second_mon_index < monitors_sizes.length; second_mon_index++) {
                if (first_mon_index != second_mon_index) {
                    var first_mon_index_sizes = monitors_sizes[first_mon_index].split(" ")
                    var second_mon_index_sizes = monitors_sizes[second_mon_index].split(" ")
                    if (parseInt(first_mon_index_sizes[0]) == parseInt(second_mon_index_sizes[0]) ||
                        parseInt(first_mon_index_sizes[0]) == parseInt(second_mon_index_sizes[1]) ||
                        parseInt(first_mon_index_sizes[1]) == parseInt(second_mon_index_sizes[0]) ||
                        parseInt(first_mon_index_sizes[1]) == parseInt(second_mon_index_sizes[1])) {
                        if (pairs.includes(`${first_mon_index} - ${second_mon_index}`) == false && pairs.includes(`${second_mon_index} - ${first_mon_index}`) == false) {
                            pairs.push(`${first_mon_index} - ${second_mon_index}`)
                            if (deleted_sizes.indexOf(monitors_sizes[first_mon_index]) !== -1) {
                                var mid_arr = old_arr.filter(word => word == monitors_sizes[first_mon_index])
                                if (mid_arr.length > 1) {
                                    count_factorial_combinations += mid_arr.length - 1
                                }
                            }
                            if (deleted_sizes.indexOf(monitors_sizes[second_mon_index]) !== -1) {
                                var mid_arr = old_arr.filter(word => word == monitors_sizes[second_mon_index])
                                if (mid_arr.length > 1) {
                                    count_factorial_combinations += mid_arr.length - 1
                                }
                            }
                        }

                    }
                }
            }
        }

    }
    console.log(pairs.length + count_factorial_combinations)
}

start();

var readline = require('readline');

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

var count_of_monitors
var monitors_sizes = []
function start() {
    rl.question("", function(answer) {
        count_of_monitors = parseInt(answer)
        get_mon()
    });
}

function get_monitors() {
    rl.question("", function(answer) {
        monitors_sizes.push(answer)
        count_of_monitors--
        get_mon()
    });

}

function get_mon() {
    if (count_of_monitors > 0) {
        get_monitors()
    } else {
        get_pairs()
    }
}

function factorial(n) {
  return (n != 1) ? n * factorial(n - 1) : 1;
}

function get_pairs() {
    var pairs = []
    var count_factorial_combinations = 0
    var deleted_sizes = []
    var old_arr = monitors_sizes
    for (var i = 0; i < monitors_sizes.length; i++) {
        var fact_arr = monitors_sizes.filter(size => size == monitors_sizes[i])
        if (fact_arr.length > 1) {
            count_factorial_combinations += factorial(fact_arr.length)
            monitors_sizes = monitors_sizes.filter((word, index) => {

                if (word == monitors_sizes[i]) {
                    if (index == i) {
                        return true
                    } else {
                        deleted_sizes.push(monitors_sizes[i])
                        return false
                    }
                } else {
                    return true
                }
            })
        }
    }
    for (var first_mon_index = 0; first_mon_index < monitors_sizes.length; first_mon_index++) {
        for (var second_mon_index = first_mon_index + 1; second_mon_index < monitors_sizes.length; second_mon_index++) {
            if (first_mon_index != second_mon_index) {
                var first_mon_index_sizes = monitors_sizes[first_mon_index].split(" ")
                var second_mon_index_sizes = monitors_sizes[second_mon_index].split(" ")
                if (parseInt(first_mon_index_sizes[0]) == parseInt(second_mon_index_sizes[0]) ||
                    parseInt(first_mon_index_sizes[0]) == parseInt(second_mon_index_sizes[1]) ||
                    parseInt(first_mon_index_sizes[1]) == parseInt(second_mon_index_sizes[0]) ||
                    parseInt(first_mon_index_sizes[1]) == parseInt(second_mon_index_sizes[1])) {
                    if (pairs.includes(`${first_mon_index} - ${second_mon_index}`) == false && pairs.includes(`${second_mon_index} - ${first_mon_index}`) == false) {
                        pairs.push(`${first_mon_index} - ${second_mon_index}`)
                        if (deleted_sizes.indexOf(monitors_sizes[first_mon_index]) !== -1) {
                            var mid_arr = old_arr.filter(word => word == monitors_sizes[first_mon_index])
                            if (mid_arr.length > 1) {
                                count_factorial_combinations += mid_arr.length - 1
                            }
                        }
                        if (deleted_sizes.indexOf(monitors_sizes[second_mon_index]) !== -1) {
                            var mid_arr = old_arr.filter(word => word == monitors_sizes[second_mon_index])
                            if (mid_arr.length > 1) {
                                count_factorial_combinations += mid_arr.length - 1
                            }
                        }
                    }

                }
            }
        }
    }
    console.log(pairs.length + count_factorial_combinations)
}

start();

var n = readline();
var pairs = []
var pairsCount = 0
var r = 0

for (var i = 0; i < n; i++) {
	var l = readline().split(' ')

	var c = pairs.filter(el => el.includes(l[0]) || el.includes(l[1])).length;

	if (c > 1) {
		r += c
	}

	pairs.push(l)
}

print(r);

var n = readline();
var pairs = []
var pairsCount = 0
var r = 0

for (var i = 0; i < n; i++) {
	var l = readline().split(' ')

	var c = pairs.filter(el => el.includes(l[0]) || el.includes(l[1])).length;

	if (c > 1) {
		r += c
	}

	pairs.push(l)
}

print(r * (r - 1) / 2);

var n = readline();
var numbers = []

for (var i = 0; i < n; i++) {
	var l = readline().split(' ');

	if (l[0] === l[1]) {
		numbers.push(l[0])
	} else {
		numbers = numbers.concat(l)
	}
}

var r = 0

while (numbers.length) {
	var currNumber = numbers[0]
	var l = numbers.length
	numbers = numbers.filter(el => el !== currNumber)
	var l = l - numbers.length

	if (l > 1) {
		r += (l * (l - 1)) / 2
	}
}

print(r);

var n = readline();
var numbers = []

for (var i = 0; i < n; i++) {
	var l = readline().split(' ');

	if (l[0] === l[1]) {
		numbers.push(l)
	} else {
		numbers = numbers.concat(l)
	}
}

var r = 0

while (numbers.length) {
	var currNumber = numbers[0]
	var l = numbers.length
	numbers = numbers.filter(el => el !== currNumber)
	var l = l - numbers.length

	if (l > 1) {
		r += (l * (l - 1)) / 2
	}
}

print(r);

var n = readline();
var numbers = []

for (var i = 0; i < n; i++) {
	var l = readline().split(' ');

	if (l[0] === l[1]) {
		numbers.push(l)
	} else {
		numbers.push(...l)
	}
}

var r = 0

while (numbers.length) {
	var currNumber = numbers[0]
	var l = numbers.length
	numbers = numbers.filter(el => el !== currNumber)
	var l = l - numbers.length

	if (l > 1) {
		r += (l * (l - 1)) / 2
	}
}

print(r);

var n = readline();
var numbers = {}

for (var i = 0; i < n; i++) {
	var l = readline().split(' ');

	if (l[0] === l[1]) {
		if (numbers[l[0]]) {
			numbers[l[0]] = numbers[l[0]] + 1;
		} else {
			numbers[l[0]] = 1
		}
	} else {
		l.forEach(el => {
			if (numbers[el]) {
				numbers[el] = numbers[el] + 1;
			} else {
				numbers[el] = 1
			}
		})
	}
}

print("1");


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++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    let i = 0
    let j = n - 1
    while (i < j) {
        while (i < j) {
            if (arr[i] > 0) break
            i++
        }
        while (i < j) {
            if (arr[j] < 0) break
            j--
        }
        if (i > j) break
        arr[i] = -arr[i]
        arr[j] = -arr[j]
        i++; j--
    }
// console.log(arr)
    for (i = 1; i < arr.length; i++) {
        if (arr[i] < arr[i - 1]) return 'NO'
    }
    return 'YES'
}

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() {
  let t = parseInt(readLine());

  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let arr = readLine().split(" ").map(Number);

    let cntNegative = 0,
      ispresent = 0;
    for (let x of arr) {
      if (x < 0) {
        cntNegative++;
        ispresent = 1;
      }
    }

    let j = 0;
    for (let i = 0; i < arr.length; i++) {
      if (cntNegative > 0 && arr[i] > 0) {
        arr[i] *= -1;
        cntNegative--;
        j = i;
      } else if (cntNegative > 0 && arr[i] < 0) {
        cntNegative--;
        j = i;
      }
    }

    for (let k = j + 1; ispresent && k < arr.length; k++) {
      if (arr[k] < 0) {
        arr[k] *= -1;
      }
    }
    let flag = 0;
    for (let i = 1; i < arr.length; i++) {
      if (arr[i - 1] > arr[i]) {
        console.log("NO");
        flag = 1;
        break;
      }
    }

    if (flag == 0) {
      console.log("YES");
    }
  }
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
var alpha = []
var num = []
function alph() {
  var g = []
  var f = 'abcdefghijklmnopqrstuvwxyz';
  for(var x=0;x<f.length;x++) {
    num[f[x]] = x+1;
    alpha[x+1] = f[x]
  }
  //return g;
}
function Alph() {
  var g = []
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  for(var x=0;x<f.length;x++) {
    num[f[x]] = x+1;
    alpha[x+1] = f[x];
  }
  //return g;
}
var T = readline();
for(var q=1;q<=T;q++) {
  var n = readline();
  //var n = a.length;
  var a = readline().split(' ').map((x)=> parseInt(x))
  var j = 0;
  for(var i=n-1;i>=0 && i>j;i--) {
    if(a[i] < 0) {
      if(a[j] > 0) {
        a[j] = a[j] * (-1);
        a[i] = a[i] * (-1)
        j++;
      } else {
        //if(q == 3) console.log([a[i],a[j]])
        while(a[j] < 0 && j < n) j++;
        if(i <= j) continue;
        if(j < n && a[j] > 0) {
          //if(q == 3) console.log([a[i],a[j]])
          a[j] = a[j] * (-1)
          a[i] = a[i] * (-1)
          j++;
        }

      }
    }
  }
  var ok = true;
  for(var i=1;i<n;i++) {
    if(a[i] < a[i-1]) {
      ok = false;
      break;
    }
  }
  var ans = ok ? 'YES' : 'NO';
  console.log(ans);
  //fs.appendFileSync('output.txt', ans+'\r\n');

  //os.EOL
}

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a) {
  for (let i = n - 1, j = n - 2; i >= 0; i--) {
    var _a2;
    if (a[i] < 0) {
      var _a;
      if (Math.abs(a[i]) <= ((_a = a[i + 1]) !== null && _a !== void 0 ? _a : Infinity)) {
        if (j >= i) j = i - 1;
        while (j >= 0 && a[j] < 0) {
          j--;
        }
        if (j >= 0) {
          a[i] = -a[i];
          a[j] = -a[j];
        }
      }
    }
    if (a[i] > ((_a2 = a[i + 1]) !== null && _a2 !== void 0 ? _a2 : Infinity)) {
      console.log('NO');
      return;
    }
  }
  console.log('YES');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);

        let neg = arr.filter(n => n < 0).length;

        const getNum = k => {
            let num = Math.abs(arr[k]);
            if (k < neg) {
                num = -num;
            }
            return num;
        }

        let no = false;
        for (let i = 0; i < arr.length; i++) {
            let num = getNum(i);
            if (i > 0 && num < getNum(i - 1)) {
                no = true;
                break;
            }
        }

        output(no ? 'NO' : 'YES');
    }
}

/*
 * File Created: Thursday, 11th February 2021 1:42:08 pm
 * Author: Lukas Rimkus
 */
'use-strict'

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();
        const arr = data.shift().split(' ').map(Number);

        console.log(a(n,arr));
    }
});

function get_ints() {
    return data[currentLine++].split(' ').map(Number);
}

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

function a(n,arr){
    let k = 0;
    let j = 0;
    for(let i = 0 ; i < n; i++){
        if(arr[i] < 0){
            arr[j++] *= -1;
            arr[i] *= -1;
        }
    }
    if(isSorted(arr)) {
        return 'YES';
    } else {
        return 'NO'
    }
}

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

module.exports = a;

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

let ls = [];

function solve() {
    let l = 0;
    let t = parseInt(ls[l++]);
    for (; t > 0; t--){
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(it => parseInt(it));
        let j = 0;
        for (let i = 0; i < n; i++){
            if (a[i] < 0){
                a[j++] *= -1;
                a[i] *= -1;
            }
        }

        let isSorted = true;
        for (let i = 1; i < n; i++){
            if (a[i] < a[i - 1]){
                isSorted = false;
                break;
            }
        }

        if (isSorted){
            console.log('YES');
        }
        else{
            console.log('NO');
        }
    }
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

/*---------------------------------------------------*/

const calc = (n, a)=>{
    let neg = 0;
    let pos = 0;

    for (let i = 0; i < n; i++) {
        if (a[i] < 0) neg++;
        else pos++;
    }

    for (let i = 0; i < n; i++) {
        if (i < neg && a[i] > 0) {
            a[i] = -a[i];
        }
        if (i >= neg && a[i] < 0) {
            a[i] = -a[i];
        }
        if (i > 0 && a[i] < a[i - 1]) return 'NO';
    }

    return 'YES';
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        // let [n, k] = ra();
        let a = ra();
        console.log(`${calc(n, a)}`);
    }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	// console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

function Main(){
    // input in nodeJs
	var t = nextInt();
	while(hasNext()){
		solve();
	}
}

function solve() {
    const size = nextInt();
    const arr = nextIntArray(size);

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

    for (let i = 0; i < arr.length; i++) {

        if (negative > 0) {
            arr[i] = -Math.abs(arr[i]);
            negative--;
        } else if (negative === 0) {
            arr[i] = Math.abs(arr[i]);
        }
    }

    for (let i = 0; i < arr.length-1; i++) {
        if (arr[i] > arr[i+1]) {
            myout("NO");
            return;
        }
    }

    myout("YES")
}

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let A = ra();
  LT({n, A});

  // PROCESSING:
  let minuses = 0;
  for (let i=0; i<n; i++)
    if (A[i]<0)
      minuses++;
  for (let i=0; i<n; i++){
    if (i<minuses){
      A[i] = -Math.abs(A[i])
    } else
      A[i] = Math.abs(A[i])
  }
  for (let i=0; i<n-1; i++){
    if (A[i]>A[i+1])
      return 'NO'
  }
  return 'YES';
};

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() {
  let t = parseInt(readLine());

  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let arr = readLine().split(" ").map(Number);

    let cntNegative = 0,
      ispresent = 0;
    for (let x of arr) {
      if (x < 0) {
        cntNegative++;
        ispresent = 1;
      }
    }

    let j = 0;
    for (let i = 0; i < arr.length; i++) {
      if (cntNegative > 0 && arr[i] > 0) {
        arr[i] *= -1;
        cntNegative--;
        j = i;
      } else if (cntNegative > 0 && arr[i] < 0) {
        cntNegative--;
        j = i;
      }
    }

    for (let k = j + 1; ispresent && k < arr.length; k++) {
      if (arr[i] < 0) {
        arr[k] *= -1;
      }
    }
    let flag = 0;
    for (let i = 1; i < arr.length; i++) {
      if (arr[i - 1] > arr[i]) {
        console.log("NO");
        flag = 1;
        break;
      }
    }

    if (flag == 0) {
      console.log("YES");
    }
  }
}

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() {
  let t = parseInt(readLine());

  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let arr = readLine().split(" ").map(Number);

    let cntNegative = 0,
      ispresent = 0;
    for (let x of arr) {
      if (x < 0) {
        cntNegative++;
        ispresent = 1;
      }
    }

    let j = 0;
    for (let i = 0; i < arr.length; i++) {
      if (cntNegative > 0 && arr[i] > 0) {
        arr[i] *= -1;
        cntNegative--;
        j = i;
      } else if (cntNegative > 0 && arr[i] < 0) {
        cntNegative--;
        j = i;
      }
    }

    for (let k = j + 1; ispresent && k < arr.length; k++) {
      arr[k] *= -1;
    }
    let flag = 0;
    for (let i = 1; i < arr.length; i++) {
      if (arr[i - 1] > arr[i]) {
        console.log("NO");
        flag = 1;
        break;
      }
    }

    if (flag == 0) {
      console.log("YES");
    }
  }
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
var alpha = []
var num = []
function alph() {
  var g = []
  var f = 'abcdefghijklmnopqrstuvwxyz';
  for(var x=0;x<f.length;x++) {
    num[f[x]] = x+1;
    alpha[x+1] = f[x]
  }
  //return g;
}
function Alph() {
  var g = []
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  for(var x=0;x<f.length;x++) {
    num[f[x]] = x+1;
    alpha[x+1] = f[x];
  }
  //return g;
}
var T = readline();
for(var q=1;q<=T;q++) {
  var n = readline();
  //var n = a.length;
  var a = readline().split(' ').map((x)=> parseInt(x))
  var j = 0;
  for(var i=n-1;i>=0 && i>j;i--) {
    if(a[i] < 0) {
      if(a[j] > 0) {
        a[j] = a[j] * (-1);
        a[i] = a[i] * (-1)
        j++;
      } else {
        //if(q == 3) console.log([a[i],a[j]])
        while(a[j] < 0 && j < n) j++;
        if(j < n && a[j] > 0) {
          //if(q == 3) console.log([a[i],a[j]])
          a[j] = a[j] * (-1)
          a[i] = a[i] * (-1)
          j++;
        }
      }
    }
  }
  var ok = true;
  for(var i=1;i<n;i++) {
    if(a[i] < a[i-1]) {
      ok = false;
      break;
    }
  }
  var ans = ok ? 'YES' : 'NO';
  console.log(ans);
  //fs.appendFileSync('output.txt', ans+'\r\n');

  //os.EOL
}

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a) {
  for (let i = n - 1, j = n - 2; i >= 0; i--) {
    var _a2;
    if (a[i] < 0) {
      var _a;
      if (Math.abs(a[i]) < ((_a = a[i + 1]) !== null && _a !== void 0 ? _a : Infinity)) {
        if (j >= i) j = i - 1;
        while (j >= 0 && a[j] < 0) {
          j--;
        }
        if (j >= 0) {
          a[i] = -a[i];
          a[j] = -a[j];
        }
      }
    }
    if (a[i] > ((_a2 = a[i + 1]) !== null && _a2 !== void 0 ? _a2 : Infinity)) {
      console.log('NO');
      return;
    }
  }
  console.log('YES');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();


var line = readline();
var P=[];
var n = 0;

var subline = line;

while(subline.match("bear")){
    var pos = subline.search("bear");
    if(P.length>0){P.push(P[P.length-1]+4+pos);}
    else{P.push(pos)}
    subline = subline.substring(pos+4,subline.length);
}

if(P.length>0){
  n = (P[0]+1)*(line.length -P[0]-3);
  for(var i=1;i<P.length;i++){
    n = n + (P[i]-P[i-1])*(line.length-P[i]-3);
  }

}

print(n);

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

if(a.hasOwnProperty(0)){

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}else{
	print(0);
}

}

;(function () {

	print((function () {
		var s = readline(), n = s.length, p = s.indexOf('bear'), l = 0, k = -1;

		while (p !== -1) {
			l += Math.max(p - k, 1) * (n - p - 3);
			k = p; p = s.indexOf('bear', p + 1);
		}

		return l;
	})());

}).call(this)

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var s = trim(readline());

	var bearIndices = [];
	var isBearIndex = new Array(s.length);
	var startIndex = 0;
	while (true) {
		var foundIndex = s.indexOf("bear", startIndex);
		if (foundIndex == -1) {
			break;
		}
		bearIndices.push(foundIndex);
		isBearIndex[foundIndex] = true;
		startIndex = foundIndex+1;
	}

	var count = 0;
	for (var pos = 0; pos < s.length; pos += 1) {
		var found = false;
		for (var seek = pos; seek < s.length; seek += 1) {
			if (isBearIndex[seek]) {
				found = true;
				break;
			}
		}
		if (found) {
			count += s.length-seek-3;
		}
	}

	print(count);
}

main();

var line = readline();
var result = 0;
var occurrences = [];

var foundBears = [];
for (var i = 0; i < line.length; i++) {
  if (line.slice(i, i + 4) == "bear") {
    result += line.length - (i + 3);
    // print(i, result);
    result += i * (line.length - (i + 3));
    // print(i, result);

    if (foundBears.length > 0) {
      var lastBear = foundBears[foundBears.length - 1];
      result -= (lastBear + 1) * (line.length - (i + 3));
    }

    foundBears.push(i);
    // print(i, result);
    // print();
  }
}

print(result);

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

if(a[0]){

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}else{
	print(n);
}

}

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

if(a.hasOwnProperty(0)){

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}else{
	print(n);
}

}

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
print(n)
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}

;(function () {

	var s = readline(), n = s.length, r = /bear/, k = 4, l = 0, i, j;

	for (i = 0; i < n - k; i++)
		for (j = i + k; j <= n; j++)
			l += r.test(s.slice(i, j));

	print(l);

}).call(this)


Я=readline().split(' ')
бьенториш=+Я[0]
чукча=+Я[1]
цваф=readline().split(' ').map(function(щшо){return +щшо})
ногнг=new Array(бьенториш-1)
for (и=1;и<бьенториш;и++)
    ногнг[и-1]=цваф[и]-цваф[и-1]

function срака(елда,манда)
{
    if (елда>манда)
    return -1
    if (елда==манда)
    return 0
    return 1
}

ногнг.sort(срака)
чукча-=1
ответ=цваф[бьенториш-1]-цваф[0]
for (i=0;i<чукча;i++)
ответ-=ногнг[i]

print(ответ)

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {
    var input = rdAr();
    var n = input[0];
    var k = input[1];
    var A = rdAr();
    var U = Array.from(new Set(A));
    if (U.length <= k) {
        wr(0);
    } else {
        var D = [];
        for (var i = 1; i < U.length; ++i) {
            D.push(U[i] - U[i - 1]);
        }
        D.sortLt();
        var res = 0;
        for (var i = 0; i < D.length - (k-1); ++i) {
            res += D[i];
        }
        wr(res);
    }
};

if (INPUT) {
INPUT = INPUT.split('\n').reverse();
readline = () => INPUT.pop();
write = (s) => {OUTPUT += s};
print = (s) => {OUTPUT += s + '\n'};
}
const rd = readline;
const wr = write;
const pr = print;
const rdAr = () => rd().split(' ').map(v => +v);
const prAr = (a) => pr(a.join(' '));
const cmpLt = (a, b) => a - b;
const cmpGt = (a, b) => b - a;
Array.prototype.sortLt = function() { return this.sort(cmpLt); };
Array.prototype.sortGt = function() { return this.sort(cmpGt); };
const crAr = function(length, ...fillArgs) { return new Array(length).fill(...fillArgs); };
const getPrimes = function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(var i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;};

try {main();}finally{return OUTPUT;}
})();


let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var a = lines[i];
        for(l = 1; l <= a; l++){
            var ans = '';
            for(j = 1; j <= l; j++){
                if(j == 1 || j == l){
                    ans += 1 + ' ';
                }else{
                    ans += 0 + ' ';
                }
            }
            console.log(ans);
        }
    }
});

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
     let t = parseInt(readline());
     while(t--){
          let n = parseInt(readline());
          let res = [];
          for(let i=0;i<n;i++){
               if(i===0) res.push([1]);
               else if(i===1) res.push([1,1]);
               else if(i===2) res.push([1,0,1]);
               else{
                    let k = []
                    for(let j=0;j<i+1;j++){
                              if(j===0 || j===i) k.push(1);
                              else k.push(0);
                         }
                    res.push(k);
               }
          }
          for(let i=0;i<res.length;i++) console.log(res[i].join(" "));
     }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        for (let i = 1; i <= n; i++) {
            if (i === 1) {
                output(1);
            } else if (i===2) {
                output('1 1');
            } else {
                output('1 ' + (new Array(i - 2).fill(0).join(' ')) + ' 1');
            }
        }
    }
}

let readline = require("readline");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0] + 1) {
    // call your function here

    solve(input);
    rl.close();
  }
});

let solve = (input) => {
  for (let i = 1; i < input.length; i++) {
    let ans = ["1", "1 1"];
    if (+input[i] === 1) {
      console.log(ans[0]);
      continue;
    } else if (+input[i] === 2) {
      console.log(ans[0]);
      console.log(ans[1]);
      continue;
    }
    let n = +input[i];
    let x = 3;
    while (x <= n) {
      ans.push("1 " + "0 ".repeat(x - 2) + "1");
      x++;
    }

    for (let i = 0; i < ans.length; i++) {
      console.log(ans[i]);
    }
  }
};

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var a = lines[i];
        console.log(1);
        var ans = '';
        for(j = 0; j < a - 1; j++){
            ans += j === 0 ? 1 + ' ' : 0 + ' ';
        }
        ans += 1 + ' ';
        console.log(ans);
    }
});

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var a = lines[i];
        var ans = 1 + ' ';
        console.log(1);
        if(a == 1){
            console.log(ans);
        }else{
            for(j = 0; j < a - 2; j++){
                ans += 0 + ' ';
            }
            ans += 1;
            console.log(ans);
        }
    }
});

let readline = require("readline");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0][0] + 1) {
    // call your function here
    solve(input);
    rl.close();
  }
});

let solve = (input) => {
  for (let i = 1; i < input.length; i++) {
    let n = input[i];

    for (let j = 0; j < n; j++) {
      for (let k = 0; k < j + 1; k++) {
        if (k === 0 || k == j) {
          process.stdout.write("1 ");
        } else {
          process.stdout.write("0 ");
        }
      }
      process.stdout.write("\n");
    }
  }
};

let readline = require("readline");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0][0] + 1) {
    // call your function here
    solve(input);
    rl.close();
  }
});

let solve = (input) => {
  for (let i = 1; i < input.length; i++) {
    let ans = ["1", "1 1"];
    if (+input[i] === 1) {
      console.log(ans[0]);
      continue;
    } else if (+input[i] === 2) {
      console.log(ans[0]);
      console.log(ans[1]);
      continue;
    }
    let n = +input[i];
    let x = 3;
    while (x <= n) {
      ans.push("1 " + "0 ".repeat(x - 2) + "1");
      x++;
    }

    for (let i = 0; i < ans.length; i++) {
      console.log(ans[i]);
    }
  }
};

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
     let t = parseInt(readline());
     while(t--){
          let n = parseInt(readline());
          let res = [];
          for(let i=0;i<n;i++){
               if(i===0) res.push([1]);
               else{
                    let k = [];
                    if((i+1)%2===0){
                         for(let j=0;j<i+1;j++) k.push(1);
                    }
                    else{
                         for(let j=0;j<i+1;j++){
                              if(j===0 || j===i) k.push(1);
                              else k.push(0);
                         }
                    }
                    res.push(k);
               }
          }
          for(let i=0;i<res.length;i++) console.log(res[i].join(" "));
     }
};
solve();


var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const s = rl();

		let ans;
		for (let i = 0; i < 2; i++) {
			for (let j = 0; j < 2; j++) {
				for (let k = 0; k < 2; k++) {
					const ss = [];
					for (const c of s) {
						if (c == 'A') ss.push(i ? '(' : ')');
						if (c == 'B') ss.push(j ? '(' : ')');
						if (c == 'C') ss.push(k ? '(' : ')');
					}
					ans |= check(ss);
				}
			}
		}

		function check (ss) {
			let cnt = 0;
			for (let i = 0; i < ss.length; i++) {
				if (ss[i] == '(') cnt++;
				else cnt --;
				if (cnt < 0) break;
			}
			return cnt == 0;
		}

		console.log(ans ? 'YES' : 'NO');
	}
}

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

let standardInputString = "";
let currentLine = 0;

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

process.stdin.on("data", rawData => {
    standardInputString += rawData;
});

process.stdin.on("end", _ => {
    standardInputString = standardInputString.trim().split("\n").map(line => {
        return line.trim();
    })
    main();
});

function main() {
    let t = parseInt(readline());
    while (t--) {
        let line = readline().split("");
        console.log(processExpression(line));
    }
}
function processExpression(exp) {
    const escenarios = [
        ["(", "(", ")"],
        ["(", ")", "("],
        ["(", ")", ")"],
        [")", "(", "("],
        [")", "(", ")"],
        [")", ")", "("]
    ];
    for (const escenario of escenarios) {
        let bracket = assignBracket(exp, ...escenario).split("");
        if (isValidExpression(bracket)) {
            return "YES";
        }
    }
    return "NO";
}
function assignBracket(exp, A, B, C) {
    let newExp = "";
    for (let i = 0; i < exp.length; i++) {
        if (exp[i] == "A") {
            newExp += A;
        }
        else if (exp[i] == "B") {
            newExp += B;
        }
        else if (exp[i] == "C") {
            newExp += C;
        }
    }
    return newExp;
}
function isValidExpression(bracket) {
    for (let i = 0; i < bracket.length - 1; i++) {
        if (bracket[i] == "(" && bracket[i + 1] == ")") {
            bracket.splice(i, 2);
            return isValidExpression(bracket);
        }
    }
    return bracket.length == 0;
}

'use-strict'

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 a = readLine();

        const res = main(a);

        console.log(res)
    }
});

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

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

function main(a){
    let cnt_A = 0;
    let cnt_B = 0;
    let cnt_C = 0;
    let arr = [];
    for(let i= 0 ; i < a.length; i++){
        if(a[i] === 'A') cnt_A++;
        if(a[i] === 'B') cnt_B++;
        if(a[i] === 'C') cnt_C++;
    }
    arr.push(['A', cnt_A]);
    arr.push(['B', cnt_B]);
    arr.push(['C', cnt_C]);
    arr.sort((a,b) => a[1] - b[1]);
    let sum = 0;
    let opn = a[0];
    if(opn === arr[arr.length - 1][0]){
        // the other two are closing brackets
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    } else {
        // opn and arr[0] || arr[1] is opening and arr[arr.length - 1] are closing
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn || a[i] === arr[0][0] || a[i] === arr[1][0]){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    }

    if(sum !== 0){
        return 'NO'
    } else{
        return 'YES'
    }
}

module.exports = main;

/*
Functions used for getting input from the console

To get the next line of input when it is received use 'await getNextLine()' inside of an async function
*/

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

let input = [];
let currentLine = 0;

//adds next line to input array
process.stdin.on('data', function(inputStdin)
{
    const newIn = inputStdin.split("\n")
    for (let i of newIn)
    {
        if (i.length > 0) input.push(i.trim());
    }
});

//returns the next line of unprocessed input
function readLine()
{
    if (!isNewInput()) return "";

    return input[currentLine++];
}

//checks if any new input has been added
function isNewInput()
{
    return currentLine < input.length;
}

//waits 'ms' milliseconds
function sleep(ms)
{
    return new Promise((resolve) =>
    {
        setTimeout(resolve, ms);
    });
}

//returns the next line of unprocessed input once it is available
async function getNextLine()
{
    while(!isNewInput()) await sleep(5);
    return readLine();
}
//----------------------------------------------------

//main
main();
async function main()
{
    const testCases = Number(await getNextLine());
    for (let t = 0; t < testCases; t++)
    {
        const abc = await getNextLine();
        if (isValid(abc, ["A"], ["B", "C"]))
        {
            console.log("YES");
            //console.log("1");
            continue;
        }

        if (isValid(abc, ["B"], ["A", "C"]))
        {
            console.log("YES");
            //console.log("2");
            continue;
        }

        if (isValid(abc, ["C"], ["A", "B"]))
        {
            console.log("YES");
            //console.log("3");
            continue;
        }

        if (isValid(abc, ["A", "B"], ["C"]))
        {
            console.log("YES");
            //console.log("4");
            continue;
        }

        if (isValid(abc, ["A", "C"], ["B"]))
        {
            console.log("YES");
            //console.log("5");
            continue;
        }

        if (isValid(abc, ["C", "B"], ["A"]))
        {
            console.log("YES");
            //console.log("6");
            continue;
        }

        console.log("NO");
    }
    process.exit();
}

function isValid(seq, open, close)
{
    let count = 0;
    const arr = seq.split("");
    for (let c of arr)
    {
        if (open.includes(c))
        {
            count++;
        }
        else if (close.includes(c))
        {
            count--;
        }
        if (count < 0) return false;
    }
    return count == 0;
}

const correctBracket = str => {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "(") count += 1;
    else count -= 1;
    if (count < 0) return false;
  }
  return count === 0;
};

const solve = str => {
  for (let i = 0; i < 2 ** 3; i++) {
    const check = correctBracket(
      str
        .replace(/A/g, (i & 1) === 1 ? "(" : ")")
        .replace(/B/g, ((i >> 1) & 1) === 1 ? "(" : ")")
        .replace(/C/g, ((i >> 2) & 1) === 1 ? "(" : ")")
    );
    if (check) return "YES";
  }
  return "NO";
};

const main = () => {
  let test = readInt();
  while (test--) {
    const str = readLine();
    console.log(solve(str));
  }
};

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 => string.trim());
  main();
});

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(s));
};

'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++];
}

// Make a Snippet for the code above this and then write your logic in main();
var mod = 1000000000n + 7n
var maxN = 1002

function main() {
    const x = readline();
    //
    Array(Number(x)).fill(1).map((t, iii) => {
        // var n = parseInt(readline())
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })

        var a = readline().split('').map((x, iii) => {
            return x
        })

        var b = new Array(a.length)
        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = '('
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = '('
        }

        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = '('
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')
        console.log('NO')
        // console.log(a)

    })
}

function checkString(a) {
    // console.log(a)
    var count = 0
    var res = true
    for (let i = 0; i < a.length; i++) {
        if (a[i] === '(') count++
        else {
            count--
            if (count < 0) res = false
        }
    }
    if (count !== 0) res = false

    return res

}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var key = ["A", "B", "C"];
	for(var i = 0; i < t; i++){
		var s = next();
		var isOK = false;
		for(var j = 0; j < (1 << (key.length)); j++){
			var map = {};
			for(var k = 0; k < key.length; k++){
				if((j & (1 << k)) != 0){
					map[key[k]] = "(";
				}else{
					map[key[k]] = ")";
				}
			}
			var v = [];
			for(var k = 0; k < s.length; k++){
				if(map[s[k]] == "("){
					v.push("(");
				}else if(v.length > 0 && v[v.length - 1] == "("){
					v.pop();
				}else{
					v.push(")");
				}
			}
			if(v.length == 0){
				isOK = true;
				break;
			}
		}
		if(isOK){
			myout("YES");
		}else{
			myout("NO");
		}
	}
}

const { SSL_OP_TLS_ROLLBACK_BUG } = require("constants");
const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
let input = [];
rl.on('line', line => {
    input.push(line);
})
rl.on('close', line => {
   var n = Number(input[0]);
   for (var m = 1; m < input.length; m++) {
       var str = input[m];
    //    ["(((", "(()", "()(", "())", ")((", ")()", "))(", ")))"];
       var patterns = ["(()", "()(", "())", ")((", ")()", "))("];
       var flag = false;
       for (let pattern of patterns) {
           var count = 0;
           var i;
           for (i = 0; i < str.length; i++) {
                var c;
                if (str[i] === "A") {
                    c = pattern[0];
                } else if (str[i] === "B") {
                    c = pattern[1];
                } else {
                    c = pattern[2];
                }
                if (c === "(") {
                    count++;
                } else {
                    count--;
                }
                if (count < 0) {
                    break;
                }
           }
           if (i === str.length && count === 0) {
               flag = true;
           }
       }
       if (flag) {
           console.log("YES");
       } else {
           console.log("NO");
       }
   }
})

const T = parseInt(readline());

for (t = 0; t < T; t++) {
	var s = readline();

	var any = false;
	for (a = -1; a < 2; a += 2) {
		for (b = -1; b < 2; b += 2) {
			for (c = -1; c < 2; c += 2) {
				var cur = 0;
				var ok = true;
				for (i = 0; i < s.length; i++) {
					if (s[i] === 'A') cur += a;
					if (s[i] === 'B') cur += b;
					if (s[i] === 'C') cur += c;
					if (cur < 0) ok = false;
				}
				if (ok && cur === 0) {
					any = true;
				}
			}
		}
	}
	print(any ? "YES" : "NO");
}

let raw = ''
process.stdin.on('data', it => (raw += it)).on('end', () => {
const arr = raw.replace(/\r/g, '').trim().split('\n');
for (let i = 0, all = +arr.shift(); i < all; i++) {
  let s = arr[i]
  if (s[0] == s[s.length - 1]) {
    console.log('NO')
    continue
  }
  const obj = {}
  let max = 0, ch
  for (const it of s) if (max < (++obj[it] || (obj[it] = 1))) {
    max = obj[it]
    ch = it
  }
  const f = s[0] == ch
  s = s.replace(new RegExp(ch, 'g'), f ? '(' : ')')
  for (const it in obj) if (it !== ch) s = s.replace(new RegExp(it, 'g'), f ? ')' : '(')
  let t = s
  while ((s = t.replace(/\(\)/g, '')) != t) t = s
  console.log(s ? 'NO' : 'YES')
}
});

let raw = ''
process.stdin.on('data', it => (raw += it)).on('end', () => {
const arr = raw.replace(/\r/g, '').trim().split('\n');
for (let i = 0, all = +arr.shift(); i < all; i++) {
  const s = arr[i]
  if (s.length <= 1) {
    console.log('NO')
    continue
  }
  const obj = {}
  let max = 0, ch, cnt = 0
  for (const it of s) if (max < (++obj[it] || (obj[it] = 1))) {
    max = obj[it]
    ch = it
  }
  for (const it in obj) if (it !== ch) cnt += obj[it]
  console.log(max == cnt && s[0] != s[s.length -1] && !(s[0] !== ch && s[s.length - 1] !== ch) ? 'YES' : 'NO')
}
});

let raw = [];
process.stdin.on('data', it => raw.push(it)).on('end', () => {
  const arr = Buffer.concat(raw).toString().replace(/\r/g, '').trim().split('\n');
  for (let i = 0, all = +arr.shift(); i < all; i++) {
    if (arr[i][0] == arr[i][arr[i].length - 1]) {
      console.log('NO')
      continue
    }
    const obj = {}
    let max = 0, ch, cnt = 0
    for (const it of arr[i]) if (max < (++obj[it] || (obj[it] = 1))) {
      max = obj[it]
      ch = it
    }
    for (const it in obj) if (it !== ch) cnt += obj[it]
    console.log(max == cnt ? 'YES' : 'NO')
  }
})

let raw = '';
process.stdin.on('data', it => (raw += it)).on('end', () => {
  const arr = raw.replace(/\r/g, '').trim().split('\n');
  for (let i = 0, all = +arr.shift(); i < all; i++) {
    if (arr[i][0] == arr[i][arr[i].length - 1]) {
      console.log('NO')
      continue
    }
    const obj = {}
    let max = 0, ch, cnt = 0
    for (const it of arr[i]) if (max < (++obj[it] || (obj[it] = 1))) {
      max = obj[it]
      ch = it
    }
    for (const it in obj) if (it !== ch) cnt += obj[it]
    console.log(max == cnt ? 'YES' : 'NO')
  }
})

let raw = '';
process.stdin.on('data', it => (raw += it)).on('end', () => {
  const arr = raw.trim().split('\n');
  for (let i = 0, all = +arr.shift(); i < all; i++) {
    if (arr[i][0] == arr[i][arr[i].length - 1]) {
      console.log('NO')
      continue
    }
    const obj = {}
    let max = 0, ch, cnt = 0
    for (const it of arr[i]) if (max < (++obj[it] || (obj[it] = 1))) {
      max = obj[it]
      ch = it
    }
    for (const it in obj) if (it !== ch) cnt += obj[it]
    console.log(max == cnt ? 'YES' : 'NO')
  }
})

'use-strict'

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 a = readLine();

        const res = main(a);

        console.log(res)
    }
});

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

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

function main(a){
    let cnt_A = 0;
    let cnt_B = 0;
    let cnt_C = 0;
    let arr = [];
    for(let i= 0 ; i < a.length; i++){
        if(a[i] === 'A') cnt_A++;
        if(a[i] === 'B') cnt_B++;
        if(a[i] === 'C') cnt_C++;
    }
    arr.push(['A', cnt_A]);
    arr.push(['B', cnt_B]);
    arr.push(['C', cnt_C]);
    arr.sort((a,b) => a[1] - b[1]);
    console.log(arr)
    let sum = 0;
    let opn = a[0];
    if(opn === arr[arr.length - 1][0]){
        // the other two are closing brackets
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    } else {
        // opn and arr[0] || arr[1] is opening and arr[arr.length - 1] are closing
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn || a[i] === arr[0][0] || a[i] === arr[1][0]){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    }

    if(sum !== 0){
        return 'NO'
    } else{
        return 'YES'
    }
}

module.exports = main;

'use-strict'

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 a = readLine();

        const res = main(a);

        console.log(res)
    }
});

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

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

function main(a){
    let cnt_A = 0;
    let cnt_B = 0;
    let cnt_C = 0;
    let arr = [];
    for(let i= 0 ; i < a.length; i++){
        if(a[i] === 'A') cnt_A++;
        if(a[i] === 'B') cnt_B++;
        if(a[i] === 'C') cnt_C++;
    }
    arr.push(['A', cnt_A]);
    arr.push(['B', cnt_B]);
    arr.push(['C', cnt_C]);
    arr.sort((a,b) => a[1] - b[1]);
    let sum = 0;
    let opn = a[0];
    if(opn === arr[arr.length - 1][0]){
        // the other two are closing brackets
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    } else {
        // opn and arr[0] || arr[1] is opening and arr[arr.length - 1] are closing
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn || a[i] === arr[0][0] || arr[1][0]){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    }

    if(sum !== 0){
        return 'NO'
    } else{
        return 'YES'
    }
}

module.exports = main;

'use-strict'

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 a = readLine();

        const res = main(a);

        console.log(res)
    }
});

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

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

function main(a){
    if(a.length % 2 === 1 || a[0] === a[a.length - 1]){
        return 'NO';
    }
    let count_a = 0;
    let count_b = 0;
    let count_c = 0;
    let arr = [];
    for(let i = 0 ; i < a.length; i++){
        if(a[i] === 'A') count_a++;
        if(a[i] === 'B') count_b++;
        if(a[i] === 'C') count_c++;
        if(i === a.length - 1){
            arr.push(count_a);
            arr.push(count_b);
            arr.push(count_c);
            arr.sort((a,b) => a - b);
        }
    }
    if(arr[2] === (arr[0] + arr[1])){
        return 'YES';
    } else {
        return 'NO';
    }
}

module.exports = main;

'use-strict'

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 a = readLine();

        const res = main(a);

        console.log(res)
    }
});

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

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

function main(a){
    if(a.length % 2 === 1){
        return 'NO';
    }
    let count_a = 0;
    let count_b = 0;
    let count_c = 0;
    for(let i = 0 ; i < a.length; i++){
        if(a[i] === 'A') count_a++;
        if(a[i] === 'B') count_b++;
        if(a[i] === 'C') count_c++;
    }
    const is_even_count_a = count_a % 2;
    const is_even_count_b = count_b % 2;
    const is_even_count_c = count_c % 2;
    const sum = is_even_count_a + is_even_count_b + is_even_count_c;
    if(sum === 3 || sum === 1){
        return 'NO'
    } else {
        return 'YES'
    }
}

/*
Functions used for getting input from the console

To get the next line of input when it is received use 'await getNextLine()' inside of an async function
*/

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

let input = [];
let currentLine = 0;

//adds next line to input array
process.stdin.on('data', function(inputStdin)
{
    const newIn = inputStdin.split("\n")
    for (let i of newIn)
    {
        if (i.length > 0) input.push(i.trim());
    }
});

//returns the next line of unprocessed input
function readLine()
{
    if (!isNewInput()) return "";

    return input[currentLine++];
}

//checks if any new input has been added
function isNewInput()
{
    return currentLine < input.length;
}

//waits 'ms' milliseconds
function sleep(ms)
{
    return new Promise((resolve) =>
    {
        setTimeout(resolve, ms);
    });
}

//returns the next line of unprocessed input once it is available
async function getNextLine()
{
    while(!isNewInput()) await sleep(5);
    return readLine();
}
//----------------------------------------------------

//main
main();
async function main()
{
    const testCases = Number(await getNextLine());
    for (let t = 0; t < testCases; t++)
    {
        const abc = await getNextLine();
        if (isValid(abc, ["A"], ["B", "C"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["B"], ["A", "C"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["C"], ["A", "C"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["A", "B"], ["C"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["A", "C"], ["B"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["C", "B"], ["A"]))
        {
            console.log("YES");
            continue;
        }

        console.log("NO");
    }
    process.exit();
}

function isValid(seq, open, close)
{
    let count = 0;
    const arr = seq.split("");
    for (let c of arr)
    {
        if (open.includes(c))
        {
            count++;
        }
        else if (close.includes(c))
        {
            count--;
        }
        if (count < 0) return false;
    }
    return count == 0;
}

const correctBracket = str => {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "(") count += 1;
    else count -= 1;
    if (count < 0) return false;
  }
  return count === 0;
};

const solve = str => {
  const check =
    correctBracket(
      str
        .replace(/C/g, "A")
        .replace(/A/g, "(")
        .replace(/B/g, ")")
    ) ||
    correctBracket(
      str
        .replace(/C/g, "B")
        .replace(/A/g, "(")
        .replace(/B/g, ")")
    ) ||
    correctBracket(
      str
        .replace(/C/g, "A")
        .replace(/A/g, ")")
        .replace(/B/g, "(")
    ) ||
    correctBracket(
      str
        .replace(/C/g, "B")
        .replace(/A/g, ")")
        .replace(/B/g, "(")
    );
  if (check) return "YES";
  return "NO";
};

const main = () => {
  let test = readInt();
  while (test--) {
    const str = readLine();
    console.log(solve(str));
  }
};

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 => string.trim());
  main();
});

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(s));
};

'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++];
}

// Make a Snippet for the code above this and then write your logic in main();
var mod = 1000000000n + 7n
var maxN = 1002

function main() {
    const x = readline();
    //
    Array(Number(x)).fill(1).map((t, iii) => {
        // var n = parseInt(readline())
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })

        var a = readline().split('').map((x, iii) => {
            return x
        })

        var b = new Array(a.length)
        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = '('
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = '('
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')
        console.log('NO')
        // console.log(a)

    })
}

function checkString(a) {
    // console.log(a)
    var count = 0
    var res = true
    for (let i = 0; i < a.length; i++) {
        if (a[i] === '(') count++
        else {
            count--
            if (count < 0) res = false
        }
    }
    if (count !== 0) res = false

    return res

}


function resolve(k, n) {
  k = parseInt(k, 10);
  var sum = 0;
  for (var i = 0; i < n.length; i++) {
    sum += parseInt(n[i], 10);
  }
  if (sum >= k) {
    return 0;
  } else {
    var total = k - sum;
    var count = 0;
    var arr = n.split('').sort();
    for (var j = 0; j < arr.length; j++) {
      count++;
      total -= 9 - parseInt(arr[j], 10);
      if (total <= 0) {
        break;
      }
    }
    if (total > 0) {
      var q = Math.floor(total / 9);
      var r = total % 9;
      if (r === 0) {
        return q + count;
      } else {
        return q + count + 1;
      }
    } else {
      return count;
    }
  }
}

const k = readline();
const n = readline();

const result = resolve(k, n);

print(result + '\n');

function main() {
  var k = Number(readline());
  var n = readline();

  var sumOfN = n.split('').reduce((sum, i) => {
    return sum + Number(i);
  }, 0);

  if (sumOfN >= k) {
    return print(0);
  }

  var sortedN = n
    .split('')
    .sort()
    .join('');
  var changes = 0;

  for (var i = 0; i < sortedN.length; i++) {
    if (Number(sortedN[i]) !== 9) {
      sumOfN += 9 - Number(sortedN[i]);
      changes++;

      if (sumOfN >= k) {
        return print(changes);
      }
    }
  }

  print('Something went wrong');
}

main();

function resolve(k, n) {
  k = parseInt(k, 10);
  var sum = 0;
  for (var i = 0; i < n.length; i++) {
    sum += parseInt(n[i], 10);
  }
  if (sum >= k) {
    return 0;
  } else {
    var q = Math.floor((k - sum) / 9);
    var r = (k - sum) % 9;
    if (r === 0) {
      return q;
    } else {
      return q + 1;
    }
  }
}

const k = readline();
const n = readline();

const result = resolve(k, n);

print(result);

function sumDigits(number) {
  var total = 0;
  for (var i = 0; i < number.length; i++) {
    total += number[i];
  }
  return total;
}

function main() {
  var k = readline();
  var n = readline();

  var sumOfN = sumDigits(n);

  if (k < sumOfN) {
    return print(0);
  }

  var sortedN = n
    .split('')
    .sort()
    .join('');
  var newTotal = sumOfN;
  var changes = 0;

  for (var i = 0; i < sortedN.length; i++) {
    if (sortedN[i] !== '9') {
      newTotal += 9 - sortedN[i];
      changes++;
    }
  }

  print(changes);
}

main();

function main() {
  var k = readline();
  var n = readline();

  var sumOfN = n.split('').reduce((sum, i) => {
    return sum + i;
  }, 0);

  if (sumOfN >= k) {
    return print(0);
  }

  var sortedN = n
    .split('')
    .sort()
    .join('');
  var changes = 0;

  for (var i = 0; i < sortedN.length; i++) {
    if (sortedN[i] !== '9') {
      sumOfN += 9 - sortedN[i];
      changes++;

      if (sumOfN >= k) {
        return print(changes);
      }
    }
  }

  print(changes);
}

main();