const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
const n = parseInt(input[0], 10);
let secondLine = input[1].split(' ');
secondLine = secondLine.map((a) => parseInt(a, 10));
let expected = n;
const reserve = {};
let text = '';

for (let i=0; i<n; i++) {
  const size = secondLine[i];
  if (size === expected) {
    let line = size.toString();
    expected --;
    while (reserve[expected]) {
      line += ` ${expected}`;
      delete reserve[expected];
      expected --;
    }
    text += line;
  } else {
    reserve[size] = true;
  }
  text += '\n';
}
  console.log(text);
});

'use strict';

let inputString = '';

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    snackTower(inputString[0], inputString[1]);
});
function snackTower(n, snacks) {
    var snacksArr = new Array(20000);
    var largest = n;
    var str = '';
    snacks = snacks.split(' ');
    for(let i = 0; i < n; i++){
        var size = snacks[i];
        snacksArr[size] = 1;
        while(snacksArr[largest]){
            str = str + " " + largest--;
        }
        if(str){
            console.log(str);
            str = '';
        }
        else{
        console.log('');

        }

    }
}

// snackTower('10', '5 1 6 2 8 3 4 10 9 7')

var expect = parseInt(readline());
var vals = readline().split(" ").map(Number);
var temp = {};
var res = [];

for (var i = 0; i < vals.length; i++) {
    temp[vals[i]] = true;

    if (expect in temp) {
        while (expect in temp) {
            res.push(expect);
            delete temp.expect;
            expect = expect - 1;
        }

        print(res.join(" "));
        res = [];
    } else {
        print(" ");
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function print(s) {
  process.stdout.write(`${s}`);
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  // input
  const n = +readline();
  const a = readline().split(' ').map(x => parseInt(x));
  const b = new Array(n).fill(['']);
  let max = 0;
  for (let i = n - 1; i >= 0; i--) {
    if (a[i] > max) {
      b[i] = range(a[i], max);
      max = a[i];
    }
  }
  for (let i = 0; i < n; i++) {
    print(b[i].join(' ') + '\n');
  }
}
function range(hi, lo) {
  const a = [];
  while (hi > lo) {
    a.push(hi--);
  }
  return a;
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}

function array2d(r,c) {
    let ans =[];
    for(let i = 0; i < r; i++) {
        let rowElements = [];
        for(let j = 0; j < c; j++) {
            rowElements.push(0);
        }
        ans.push(rowElements);
    }
    return ans;
}
function max(a,b){
    if(a > b) return a;
    else return b;
}
function main() {
    let [n] = readint();
    let s = readint();
    let has = [...s];
    has.fill(0);
    let curr =  n - 1;
    s.forEach(element => {
        has[element - 1] = 1;
        if(element - 1 == curr) {
            const begin = curr;
            for(let i = begin; i >=0; i--) {
                if(has[i]) {
                    write((i + 1) + " ");
                    curr--;
                }
                else break;
            }
            console.log();
        } else console.log();
    });
}

var numberOfDays = Number(readline())
  var snaksPerDays = readline().split(' ').map(Number)

  var snacks = new Array(numberOfDays).fill(0)

  var index = numberOfDays
  for (var i = 0; i < numberOfDays; i++) {
    snacks[snaksPerDays[i] - 1] = 1

    var stack = []
    while(snacks[index - 1]) {
      stack.push(index)
      index -= 1
    }

    print(stack.join(' '))
  }

/*
    The idea to solve this problem is to seek whether the biggest remaining snacks has fall on that day or not,
    if the bigger snacks has fall, print them, otherwise print empty line.

    We could know the biggest remaining snack by exploiting the fact that the size of the snack given
    will be always 1..n
*/

var n = parseInt(readline());
var sizes = readline().split(' ').map(Number);
var current_max = n;

var has_fall = []; // hash table containing whether certain size snack has fall or not
var tmp = []; // temp array for printing single line by using print() in js

for(var i = 0; i < n; i++) {

    var size = sizes[i];
    has_fall[size] = 1;

    // exploiting the fact that size will be always 1..n
    while(has_fall[current_max] === 1) {

        tmp.push(current_max);
        current_max--; // we could know the next biggest remaining snack size is this
    }

    print(tmp.join(' '));
    tmp = [];
}

"use strict";

var _slicedToArray = (function() {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;
    try {
      for (
        var _i = arr[Symbol.iterator](), _s;
        !(_n = (_s = _i.next()).done);
        _n = true
      ) {
        _arr.push(_s.value);
        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
  return function(arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError(
        "Invalid attempt to destructure non-iterable instance"
      );
    }
  };
})();

var compose = function compose() {
  for (
    var _len = arguments.length, functions = Array(_len), _key = 0;
    _key < _len;
    _key++
  ) {
    functions[_key] = arguments[_key];
  }

  return function() {
    for (
      var _len2 = arguments.length, args = Array(_len2), _key2 = 0;
      _key2 < _len2;
      _key2++
    ) {
      args[_key2] = arguments[_key2];
    }

    return functions.reduce(function(currArgs, func) {
      return func(currArgs);
    }, args);
  };
};

var lineToStringArray = function lineToStringArray(str) {
  return str.split(" ");
};
var lineToNumberArray = function lineToNumberArray(str) {
  return lineToStringArray(str).map(function(num) {
    return parseInt(num, 10);
  });
};

var readNumbersLine = compose(
  readline,
  lineToNumberArray
);
var readStringsLine = compose(
  readline,
  lineToStringArray
);

var _readNumbersLine = readNumbersLine(),
  _readNumbersLine2 = _slicedToArray(_readNumbersLine, 1),
  n = _readNumbersLine2[0];

var elements = readNumbersLine();
var needed = n;
var currElements = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (
    var _iterator = elements[Symbol.iterator](), _step;
    !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
    _iteratorNormalCompletion = true
  ) {
    var curr = _step.value;

    currElements[curr] = true;
    if (curr !== needed) {
      print("");
      continue;
    }
    var res = [];
    while (currElements[needed]) {
      res.push(needed);
      needed--;
    }
    print(res.join(" "));
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator.return) {
      _iterator.return();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

'use strict';

let inputString = '';

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

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

    snackTower(inputString[0], inputString[1]);
});

function snackTower(numberOfSnacks, snacks) {

    let outputArray = [];
    let snacksFrequencyArray = [];
    let currentMax = numberOfSnacks;
    snacks = snacks.split(" ");

    for(let index = 0 ; index < numberOfSnacks ; index++){

        snacksFrequencyArray[snacks[index]] = 1

        while (snacksFrequencyArray[currentMax]) {
            outputArray.push(currentMax);
            outputArray.push(" ")
            currentMax--;
        }

        outputArray.push("\n");
    }
    console.log(outputArray.join(""));
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function print(s) {
  process.stdout.write(`${s}`);
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  // input
  const n = +readline();
  const a = readline().split(' ').map(x => parseInt(x));
  let next = n;
  let t = [];
  for (let i = 0; i < n; i++) {
    t.unshift(a[i]);
    if (a[i] === next) {
      print(t.join(' '));
      next = t[t.length - 1] - 1;
      t = [];
    }
    print('\n');
  }
}

/**
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune,
and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city,
and the residents should build a Snacktower of them by placing snacks one on another. Of course,
big snacks should be at the bottom of the tower, while small snacks should be at the top.

Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.

However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So,
at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell.
Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.

Write a program that models the behavior of Ankh-Morpork residents.

Input
The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks.

The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Output
Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day
in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

*/

'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();
    });

    snackTower(inputString[0], inputString[1]);
});

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

function snackTower(numberOfSnacks, snacks) {

    let outputArray = [];
    snacks = snacks.split(" ");
    let frequencyMap = {};
    let outputArrayFrequencyMap = {};
    let currentMax = numberOfSnacks;
    let frequencyMapIndexs = {};
    let lastMax;
    let notSeen = {};

    for (let index = 0; index < numberOfSnacks; index++) {
        notSeen[snacks[index]] = 1
    }

    for (let index = 0; index < numberOfSnacks; index++) {

        delete notSeen[snacks[index]];

        if (snacks[index] == currentMax) {

            outputArray.push(snacks[index]);
            frequencyMapIndexs[snacks[index]] = outputArray.length - 1
            outputArray.push(" ");
            let notSeenKeys = Object.keys(notSeen)
            lastMax = currentMax;
            currentMax = notSeenKeys[notSeenKeys.length - 1];
            frequencyMap[lastMax] = currentMax ? currentMax : 0;
            snacks[index] = 0;
        }

        if (snacks[index] != currentMax && !frequencyMap[currentMax]) {

            if (index != numberOfSnacks - 1)
                outputArray.push("\n");
        }

    }

    for (let index = 0; index < outputArray.length; index++) {
        if (outputArray[index] != "\n" && outputArray[index] != " ") {
            outputArrayFrequencyMap[outputArray[index]] = index;
        }
    }

    let frequencyMapKeys = Object.keys(frequencyMap);

    for (let indexKey = frequencyMapKeys.length - 1; indexKey > -1; indexKey--) {

        for (let index = frequencyMapKeys[indexKey] - 1; index > frequencyMap[frequencyMapKeys[indexKey]]; index--) {
            outputArray.splice(outputArray.indexOf(frequencyMapKeys[indexKey]) + 1, 0, " " + index)
            //    pushArrayAfterMax.push(" ")
            //  pushArrayAfterMax.push(index)
        }
    }
    //    frequencyMap[key] = pushArrayAfterMax;
    //  pushArrayAfterMax = []

    // let frequencyMapIndexsKeys = Object.keys(frequencyMapIndexs)

    // for (let index = frequencyMapIndexsKeys.length - 1; index > -1; index--) {

    //     outputArray.splice(outputArray.indexOf(frequencyMapIndexsKeys[index]) + 1, 0, ...frequencyMap[frequencyMapIndexsKeys[index]]);
    // }

    console.log(outputArray.join(""));

}

/**
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune,
and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city,
and the residents should build a Snacktower of them by placing snacks one on another. Of course,
big snacks should be at the bottom of the tower, while small snacks should be at the top.

Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.

However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So,
at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell.
Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.

Write a program that models the behavior of Ankh-Morpork residents.

Input
The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks.

The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Output
Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day
in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

*/

'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();
    });

    snackTower(inputString[0], inputString[1]);
});

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

function snackTower(numberOfSnacks, snacks) {

    let outputArray = [];
    snacks = snacks.split(" ");
    let frequencyMap = {};
    let currentMax = numberOfSnacks;

    for (let index = 0; index < numberOfSnacks; index++) {

        if (Number(snacks[index]) == currentMax) {

            outputArray.push(snacks[index]);
            outputArray.push(" ");
            currentMax--;
        }

        if (frequencyMap[currentMax]) {

            outputArray.push(frequencyMap[currentMax]);
            outputArray.push(" ");
            currentMax--;
        }

        if (Number(snacks[index]) != currentMax && !frequencyMap[currentMax]) {

            if (index != numberOfSnacks - 1)
                outputArray.push("\n");

            frequencyMap[snacks[index]] = snacks[index];
        }

    }

    for (let index = 0; index < outputArray.length; index++) {
        if (frequencyMap[outputArray[index]])
            delete frequencyMap[outputArray[index]]
    }

    Object.keys(frequencyMap).forEach(key => {
        outputArray.push(frequencyMap[key]);
    });

    console.log(outputArray.join(""));

}

/**
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune,
and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city,
and the residents should build a Snacktower of them by placing snacks one on another. Of course,
big snacks should be at the bottom of the tower, while small snacks should be at the top.

Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.

However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So,
at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell.
Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.

Write a program that models the behavior of Ankh-Morpork residents.

Input
The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks.

The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Output
Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day
in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

*/

'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();
    });

    snackTower(inputString[0], inputString[1]);
});

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

function snackTower(numberOfSnacks, snacks) {

    let outputArray = [];
    snacks = snacks.split(" ");
    let frequencyMap = {};
    let currentMax = numberOfSnacks;

    for (let index = 0; index < numberOfSnacks; index++) {

        if (Number(snacks[index]) == currentMax) {

            outputArray.push(snacks[index]);
            outputArray.push(" ");
            currentMax--;
        }

        if (frequencyMap[currentMax]) {

            outputArray.push(frequencyMap[currentMax]);
            outputArray.push(" ");
            currentMax--;
        }

        if (Number(snacks[index]) != currentMax && !frequencyMap[currentMax]) {

            if (index != numberOfSnacks - 1)
                outputArray.push("\n");

            frequencyMap[snacks[index]] = snacks[index];
        }

    }

    for (let index = 0; index < outputArray.length; index++) {
        if (frequencyMap[outputArray[index]])
            delete frequencyMap[outputArray[index]]
    }

    let frequencyMapKeys = Object.keys(frequencyMap)

    for (let index = frequencyMapKeys.length - 1; index > -1; index--) {

        if (index != frequencyMapKeys.length - 1) {
            outputArray.push(" ");
        }

        outputArray.push(frequencyMap[frequencyMapKeys[index]]);
    }

    console.log(outputArray.join(""));

}

/**
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune,
and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city,
and the residents should build a Snacktower of them by placing snacks one on another. Of course,
big snacks should be at the bottom of the tower, while small snacks should be at the top.

Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.

However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So,
at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell.
Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.

Write a program that models the behavior of Ankh-Morpork residents.

Input
The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks.

The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Output
Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day
in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

*/

'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();
    });

    snackTower(inputString[0], inputString[1]);
});

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

function snackTower(numberOfSnacks, snacks) {

    let outputArray = [];
    snacks = snacks.split(" ");
    let frequencyMap = {};
    let currentMax = numberOfSnacks;
    let lastMax;
    let notSeen = {};

    for (let index = 0; index < numberOfSnacks; index++) {
        notSeen[snacks[index]] = 1
    }

    for (let index = 0; index < numberOfSnacks; index++) {

        delete notSeen[snacks[index]];

        if (snacks[index] == currentMax) {

            outputArray.push(snacks[index]);
            outputArray.push(" ");
            let notSeenKeys = Object.keys(notSeen)
            lastMax = currentMax;
            currentMax = notSeenKeys[notSeenKeys.length - 1];
            for(let index = lastMax -1 ; index > currentMax ; index--){
                outputArray.push(index);
                outputArray.push(" ");
            }
            snacks[index] = 0;

        }

        if (snacks[index] != currentMax && !frequencyMap[currentMax]) {

            if (index != numberOfSnacks - 1)
                outputArray.push("\n");

            //   frequencyMap[snacks[index]] = snacks[index];
        }

    }

    console.log(outputArray.join(""));

}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}

function array2d(r,c) {
    let ans =[];
    for(let i = 0; i < r; i++) {
        let rowElements = [];
        for(let j = 0; j < c; j++) {
            rowElements.push(0);
        }
        ans.push(rowElements);
    }
    return ans;
}
function max(a,b){
    if(a > b) return a;
    else return b;
}
function main() {
    let [n] = readint();
    let s = readint();
    let has = [...s];
    has.fill(0);
    let curr =  n - 1;
    s.forEach(element => {
        has[element - 1] = 1;
        if(element - 1 == curr) {
            const begin = curr;
            for(let i = begin; i >=0; i--) {
                if(has[i]) {
                    write((i + 1) + " ");
                    curr--;
                }
                else break;
            }
            console.log();
        }
    });
}

'use strict';

let inputString = '';

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    snackTower(inputString[0], inputString[1]);
});
function snackTower(n, snacks) {
    n = parseInt(n)
    // snacks = snacks.toString();
    // snacks = snacks.split(' ')
    var display = {};
    var delayed = new Array(n);
    var newDelayed = new Array(n);
    newDelayed.fill('');
    delayed.fill('');
    var delayedNumber = n;
    for (let i = 0; i < n; i++) {
        var num = n - i;
        if (snacks[i] != delayedNumber) {
            display[i] = '\n';
            console.log("\n");
            var delayedIndex = delayed.length - snacks[i];
            delayed[delayedIndex] = snacks[i];
            display[i + 1] = { queue: delayed };
        }
        else if (snacks[i] == delayedNumber) {
            var newArr = new Array(delayedNumber);
            var lastDisplayedIndex = Object.keys(display).length ? Object.keys(display).length - 1 : 0;
            var delayedNumberToDsiplayIndex = delayed.length - snacks[i];
            if (lastDisplayedIndex)
                display[lastDisplayedIndex].queue[delayedNumberToDsiplayIndex] = snacks[i];
            else {
                var delayedIndex = delayed.length - snacks[i];
                delayed[delayedIndex] = snacks[i];
                display[lastDisplayedIndex] = { queue: delayed };
            }
            newArr = display[lastDisplayedIndex].queue.slice(delayed.length - delayedNumber,n - num +1)
           var str = JSON.stringify(newArr);
           str = str.replace(/,/g,' ')
           str = str.replace(/"/g,' ')
           str = str.replace('[',' ')
           str = str.replace(']',' ')
            console.log(str);
            delayed = newDelayed;
            delayedNumber = num - 1;

        }
    }
    return 0;
}
// snackTower('3', [3,1,2])

'use strict';

let inputString = '';

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    snackTower(inputString[0], inputString[1]);
});
function snackTower(n, snacks) {
    var snacksArr = new Array(20000);
    var largest = n;
    snacks = snacks.split(' ');
    for(let i = 0; i < n; i++){
        var size = snacks[i];
        snacksArr[size] = 1;
        while(snacksArr[largest]){
            console.log(largest--);
        }
        console.log('');
    }
}

// snackTower('10', '5 1 6 2 8 3 4 10 9 7')

'use strict';

let inputString = '';

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    snackTower(inputString[0], inputString[1]);
});
function snackTower(n, snacks) {
    n = parseInt(n)
    snacks = snacks.toString();
    snacks = snacks.split(' ')
    var display = {};
    var delayed = new Array(n);
    var newDelayed = new Array(n);
    newDelayed.fill('');
    delayed.fill('');
    var delayedNumber = n;
    for (let i = 0; i < n; i++) {
        var num = n - i;
        if (snacks[i] != delayedNumber) {
            display[i] = '\n';
            console.log("\n");
            var delayedIndex = delayed.length - snacks[i];
            delayed[delayedIndex] = snacks[i];
            display[i + 1] = { queue: delayed };
        }
        else if (snacks[i] == delayedNumber) {
            var newArr = new Array(delayedNumber);
            var lastDisplayedIndex = Object.keys(display).length ? Object.keys(display).length - 1 : 0;
            var delayedNumberToDsiplayIndex = delayed.length - snacks[i];
            if (lastDisplayedIndex)
                display[lastDisplayedIndex].queue[delayedNumberToDsiplayIndex] = snacks[i];
            else {
                var delayedIndex = delayed.length - snacks[i];
                delayed[delayedIndex] = snacks[i];
                display[lastDisplayedIndex] = { queue: delayed };
            }
            newArr = display[lastDisplayedIndex].queue.slice(delayed.length - delayedNumber,n - num +1)
           var str = JSON.stringify(newArr);
           str = str.replace(/,/g,' ')
           str = str.replace(/"/g,' ')
           str = str.replace('[',' ')
           str = str.replace(']',' ')
            console.log(str);
            delayed = newDelayed;
            delayedNumber = num - 1;

        }
    }
    return 0;
}
// snackTower('3', [3,1,2])

'use strict';

let inputString = '';

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    snackTower(inputString[0], inputString[1]);
});
function snackTower(n, snacks) {
    var snacksArr = new Array(20000);
    var largest = n;
    snacks = snacks.split(' ');
    for(let i = 0; i < n; i++){
        var size = snacks[i];
        snacksArr[size] = 1;
        while(snacksArr[largest]){
            console.log(largest--);
        }
        console.log('');
    }
}

snackTower('10', '5 1 6 2 8 3 4 10 9 7')

'use strict';

let inputString = '';

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    snackTower(inputString[0], inputString[1]);
});
function snackTower(n, snacks) {
    n = parseInt(n)
    snacks = snacks.toString();
    snacks = snacks.split(' ')
    var display = {};
    var delayed = new Array(n);
    var newDelayed = new Array(n);
    newDelayed.fill('');
    delayed.fill('');
    var delayedNumber = n;
    for (let i = 0; i < n; i++) {
        var num = n - i;
        if (snacks[i] != delayedNumber) {
            display[i] = '0';
            // console.log("i");

            console.log('');
            var delayedIndex = delayed.length - snacks[i];
            delayed[delayedIndex] = snacks[i];
            display[i + 1] = { queue: delayed };
        }
        else if (snacks[i] == delayedNumber) {
            var newArr = new Array(delayedNumber);
            var lastDisplayedIndex = Object.keys(display).length ? Object.keys(display).length - 1 : 0;
            var delayedNumberToDsiplayIndex = delayed.length - snacks[i];
            if (lastDisplayedIndex)
                display[lastDisplayedIndex].queue[delayedNumberToDsiplayIndex] = snacks[i];
            else {
                var delayedIndex = delayed.length - snacks[i];
                delayed[delayedIndex] = snacks[i];
                display[lastDisplayedIndex] = { queue: delayed };
            }
            newArr = display[lastDisplayedIndex].queue.slice(delayed.length - delayedNumber,n - num +1)
           var str = JSON.stringify(newArr);
           str = str.replace(/,/g,' ')
           str = str.replace(/"/g,'')
           str = str.replace('[','')
           str = str.replace(']','')
            console.log(str);
            delayed = newDelayed;
            delayedNumber = num - 1;

        }
    }
    return 0;
}

// snackTower('3', '3 1 2')

'use strict';

let inputString = '';

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    snackTower(inputString[0], inputString[1]);
});
function snackTower(n, snacks) {
    n = parseInt(n)
    snacks = snacks.toString();
    snacks = snacks.split(' ')
    var display = {};
    var delayed = new Array(n);
    var newDelayed = new Array(n);
    newDelayed.fill('');
    delayed.fill('');
    var delayedNumber = n;
    for (let i = 0; i < n; i++) {
        var num = n - i;
        if (snacks[i] != delayedNumber) {
            display[i] = '\n';
            console.log("\n");
            var delayedIndex = delayed.length - snacks[i];
            delayed[delayedIndex] = snacks[i];
            display[i + 1] = { queue: delayed };
        }
        else if (snacks[i] == delayedNumber) {
            var newArr = new Array(delayedNumber);
            var lastDisplayedIndex = Object.keys(display).length ? Object.keys(display).length - 1 : 0;
            var delayedNumberToDsiplayIndex = delayed.length - snacks[i];
            if (lastDisplayedIndex)
                display[lastDisplayedIndex].queue[delayedNumberToDsiplayIndex] = snacks[i];
            else {
                var delayedIndex = delayed.length - snacks[i];
                delayed[delayedIndex] = snacks[i];
                display[lastDisplayedIndex] = { queue: delayed };
            }
            newArr = display[lastDisplayedIndex].queue.slice(delayed.length - delayedNumber,n - num +1)
           var str = JSON.stringify(newArr);
           str = str.replace(/,/g,' ')
           str = str.replace(/"/g,'')
           str = str.replace('[','')
           str = str.replace(']','')
            console.log(str);
            delayed = newDelayed;
            delayedNumber = num - 1;

        }
    }
    return 0;
}
// snackTower('3', '3 1 2')

var numberOfDays = Number(readline())
  var snaksPerDays = readline().split(' ').map(Number)

  var snacks = new Array(numberOfDays).fill(0)

  var index = numberOfDays
  for (var i = 0; i < numberOfDays; i++) {
    snacks[snaksPerDays[i] - 1] = 1

    var stack = []
    while(snacks[index - 1]) {
      stack.push(index)
      index -= 1
    }

    print(stack.reverse().join(' '))
  }

 var numberOfDays = Number(readline())
  var snaksPerDays = readline().split(' ').map(Number)

  var lookingFor = numberOfDays
  var stack = []
  var result = new Array(numberOfDays).fill("")
  for (var i = 0; i < numberOfDays; i++) {
    stack.push(snaksPerDays[i])

    if (snaksPerDays[i] === lookingFor) {
      result[i] = stack.reverse().join(' ')
      lookingFor -= stack.length
      stack = []
    }
  }

  for (var i = 0; i < numberOfDays; i++) {
    print(result[i])
  }

var n = parseInt(readline()),
    snacks = readline().split(' ').map(Number),
    snacks_ordered = JSON.parse(JSON.stringify(snacks)).sort(function(a, b){ return b - a }),
    tmp = [];

while(snacks_ordered.length > 0 && snacks.length > 0) {

    var current_max = snacks_ordered.shift();
    if(snacks.indexOf(current_max) !== -1) {

        while(snacks[0] !== current_max) {

            tmp.push(snacks.shift())
            print('');
        }

        tmp.push(snacks.shift()); // push current_max
        tmp.sort(function(a, b){ return b - a });

        print(tmp.join(' '));
        tmp = [];
    }
}

var expect = parseInt(readline());
var vals = readline().split(" ").map(Number);
var temp = [];

for (var i = 0; i < vals.length; i++) {
    temp.push(vals[i]);
    if (vals[i] === expect) {
        temp = temp.sort((a, b) => b - a);
        expect = temp[temp.length - 1] - 1;
        print(temp.join(" "));
        temp = [];
    } else {
        print(" ");
    }
}


function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let s = $(), n = s.length;
  let n2 = 1 << Math.ceil(Math.log2(n));
  let it = Array(n2 * 2);
  For(n2, n2 + n2 - 1, i => {
    it[i] = {
      opt: 0,
      open: s[i - n2] == '(' ? 1 : 0,
      close: s[i - n2] == ')' ? 1 : 0,
    }
  })
  // log(it)
  let merge = (l, r) => {
    let m = min(l.open, r.close)
    return {
      opt: l.opt + r.opt + m,
      open: l.open + r.open - m,
      close: l.close + r.close - m
    }
  }
  ForR(n2 - 1, 1, i => { it[i] = merge(it[i << 1], it[i << 1 | 1]) })
  // log(it)
  let query = (l, r) => {  //[l, r)
    let r1 = { opt: 0, open: 0, close: 0 };
    let r2 = { opt: 0, open: 0, close: 0 };
    for (l += n2, r += n2; l < r; l >>= 1, r >>= 1) {
      // log(res, l, r)
      if (l & 1) r1 = merge(r1, it[l++])
      // log(res)
      if (r & 1) r2 = merge(it[--r], r2)
      // log(res)
    }
    return merge(r1, r2);
  }
  let q = $(), l, r
  while (q--) {
    l = +$();
    r = +$();
    out.push(query(l - 1, r).opt * 2)
  }
  log(out.join('\n'))
}

var cad;
var Base;
var T;
function nodo(car){
    if(car){
        if(car=="("){
            this.I = 0;
            this.D = 1;
            }
        else {
            this.I = 1;
            this.D = 0;
            }
        this.mx = 0;
    }
    else {
        this.I = 0;
        this.D = 0;
        this.mx = 0;
    }
}
nodo.prototype.merge = function(a,b){
    var tmp = Math.min(a.D,b.I);
    this.mx = a.mx + b.mx + tmp;
    this.I = a.I+b.I-tmp;
    this.D = a.D+b.D-tmp;
}

function init(id,L,R){
    if(L==R) T[id] = new nodo(cad.charAt(L));
    else {
        var a = id<<1;
        var M = (L+R)>>1;
        init(a,L,M);
        init(a|1,M+1,R);
        T[id] = new nodo();
        T[id].merge(T[a],T[a|1]);
    }
}
var I,J;
function query(id, L, R){
    if(I<=L && R<=J){
	//	print("ans",L,R);
        return T[id];
        }
    else {
        var a = id<<1;
        var M = (L+R)>>1;
        if(J<=M) return query(a,L,M);
        else if(I>M) return query(a|1,M+1,R);
        else {
            var ans = new nodo();
            ans.merge(query(a,L,M),query(a|1,M+1,R));
            return ans;
        }
    }
}
function calc(sz){
	sz--;
//	print("es "+sz);
	var p = 1;
	while(p<=sz){
		p<<=1;
//  print(p);
	}
	return p<<1;
}
function main() {
	cad = next();
	var n = nextInt();
	//print(cad);
	//print(n);
	Base = new Array(cad.length+1);
	T = new Array(calc(cad.length));
	//var x = new nodo(cad.charAt(0));
	//print(x.I,x.D,x.mx);
	//print("antes");
	//print(cad.length-1);
	init(1,0,cad.length-1);

    //print("desp");
    for(var i = 0;i < n;i++){
       I = nextInt();
       //print(" I "+I);
       J = nextInt();
      // print(" * "+I+" "+J);

       I--;
       J--;
       print(query(1,0,cad.length-1).mx*2);
    }
}

var tokens = [];
var tokenPos = 0;
function next(){
    //print(tokenPos," >=", tokens.length);
	while(tokenPos >= tokens.length){
		tokens =  readline().split(/[\s]+/);
		tokenPos = 0;
		}
	//	print("lei",tokens);
	//print("es ",tokens);
//	print("retornare "+tokens[tokenPos]+"   pos "+tokenPos);
	return tokens[tokenPos++];
	}
function nextInt(){
	return parseInt(next());
}
main();

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let time = Date.now();
  let inp = input.split(/\s+/), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let s = $(), n = s.length;
  let n2 = 1 << Math.ceil(Math.log2(n));
  let it = Array(n2 * 2);
  For(n2, n2 + n2 - 1, i => {
    it[i] = {
      opt: 0,
      open: s[i - n2] == '(' ? 1 : 0,
      close: s[i - n2] == ')' ? 1 : 0,
    }
  })
  // log(it)
  let merge = (l, r) => {
    let m = min(l.open, r.close)
    return {
      opt: l.opt + r.opt + m,
      open: l.open + r.open - m,
      close: l.close + r.close - m
    }
  }
  ForR(n2 - 1, 1, i => { it[i] = merge(it[i << 1], it[i << 1 | 1]) })
  // log(it)
  let query = (l, r) => {  //[l, r)
    let res = { opt: 0, open: 0, close: 0 };
    for (l += n2, r += n2; l < r; l >>= 1, r >>= 1) {
      // log(res, l, r)
      if (l & 1) res = merge(res, it[l++])
      // log(res)
      if (r & 1) res = merge(res, it[--r])
      // log(res)
    }
    return res;
  }
  let q = $(), l, r
  while (q--) {
    l = +$();
    r = +$();
    out.push(query(l - 1, r).opt * 2)
  }
  log(out.join('\n'))
}


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

var main = function() {"use strict";
    // TODO
    var t = rdN();
    loop:while (t --> 0) {
        var n = rdN();
        var D = rdS().split('').map((v, i) => ({v: v, i: i})).sort((a,b) => {
            if (a.v != b.v) {
                return a.v - b.v;
            }
            return a.i - b.i;
        });
        //prOb(D)

        var res = crAr(n);
        var last = -1;
        var color = 1;
        var firstMissed = null;
        for (var i = 0; i < n; ++i) {
            var value = D[i].v;
            var index = D[i].i;
            if (index > last && (!firstMissed || firstMissed >= value)) {
                res[index] = color;
                last = index;
            } else if (!firstMissed) {
                firstMissed = value;
            }
        }
        var last = -1;
        var color = 2;
        for (var i = 0; i < n; ++i) {
            var value = D[i].v;
            var index = D[i].i;
            if (res[index]) {
                continue;
            }

            if (index > last) {
                res[index] = color;
                last = index;
            } else {
                pr('-');
                continue loop;
            }
        }
        pr(res.join(''));
        //wr(123)
    }
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();

"use strict";

String.prototype.getNumArray = function () {
  return String(this).split('').map(function (value) {
    return parseInt(value);
  });
};

function coloredSequences(seq) {
  var coloredSequences = [];

  for (var i = 0; i < 10; i++) {
    var coloredSequence = [];
    var p = 2;

    for (var j = 0; j < seq.length; j++) {
      if (seq[j] < i) {
        coloredSequence.push(1);
      } else if (seq[j] > i) {
        p = 1;
        coloredSequence.push(2);
      } else {
        coloredSequence.push(p);
      }
    }

    coloredSequences.push(coloredSequence);
  }

  return coloredSequences;
}

function rightColoredSequence(coloredSequences, seq) {
  for (var i = 0; i < coloredSequences.length; i++) {
    var color1Element = -1;
    var color2Element = -1;
    var right = true;
    var coloredSequence = coloredSequences[i];

    for (var j = 0; j < seq.length; j++) {
      if (coloredSequence[j] === 1) {
        if (seq[j] >= color1Element) {
          color1Element = seq[j];
        } else {
          right = false;
          break;
        }
      } else {
        if (seq[j] >= color2Element) {
          color2Element = seq[j];
        } else {
          right = false;
          break;
        }
      }
    }

    if (right) {
      return coloredSequence;
    }
  }

  return undefined;
}

function solve() {
  var length = parseInt(readline());
  var sequence = readline().getNumArray();
  var rightSequence = rightColoredSequence(coloredSequences(sequence), sequence);

  if (rightSequence === undefined) {
    write('-\n');
  } else {
    write(rightSequence.join('') + '\n');
  }
}

var n = parseInt(readline());

for (var i = 0; i < n; i++) {
  solve();
}

"use strict";

String.prototype.getNumArray = function () {
  return String(this).split('').map(function (value) {
    return parseInt(value);
  });
};

function coloredSequences(seq) {
  var coloredSequences = [];

  for (var i = 0; i < 10; i++) {
    var coloredSequence = [];
    var p = 2;

    for (var j = 0; j < seq.length; j++) {
      if (seq[j] < i) {
        coloredSequence.push(1);
      } else if (seq[j] > i) {
        p = 1;
        coloredSequence.push(2);
      } else {
        coloredSequence.push(p);
      }
    }

    coloredSequences.push(coloredSequence);
  }

  return coloredSequences;
}

function rightColoredSequence(coloredSequences, seq) {
  for (var i = 0; i < coloredSequences.length; i++) {
    var color1Element = -1;
    var color2Element = -1;
    var right = true;
    var coloredSequence = coloredSequences[i];

    for (var j = 0; j < seq.length; j++) {
      if (coloredSequence[j] === 1) {
        if (seq[j] >= color1Element) {
          color1Element = seq[j];
        } else {
          right = false;
          break;
        }
      } else {
        if (seq[j] >= color2Element) {
          color2Element = seq[j];
        } else {
          right = false;
          break;
        }
      }
    }

    if (right) {
      return coloredSequence;
    }
  }

  return undefined;
}

function solve() {
  var length = parseInt(readline());
  var sequence = readline().getNumArray();
  var rightSequence = rightColoredSequence(coloredSequences(sequence), sequence);

  if (rightSequence === undefined) {
    write('-');
  } else {
    write(rightSequence.join(''));
  }
}

var n = readline().getNumArray()[0];

for (var i = 0; i < n; i++) {
  solve();
}

"use strict";

String.prototype.getNumArray = function () {
  return String(this).split('').map(function (value) {
    return parseInt(value);
  });
};

function coloredSequences(seq) {
  var coloredSequences = [];

  for (var i = 0; i < 10; i++) {
    var coloredSequence = [];
    var p = 2;

    for (var j = 0; j < seq.length; j++) {
      if (seq[j] < i) {
        coloredSequence.push(1);
      } else if (seq[j] > i) {
        p = 1;
        coloredSequence.push(2);
      } else {
        coloredSequence.push(p);
      }
    }

    coloredSequences.push(coloredSequence);
  }

  return coloredSequences;
}

function rightColoredSequence(coloredSequences, seq) {
  for (var i = 0; i < coloredSequences.length; i++) {
    var color1Element = -1;
    var color2Element = -1;
    var right = true;
    var coloredSequence = coloredSequences[i];

    for (var j = 0; j < seq.length; j++) {
      if (coloredSequence[j] === 1) {
        if (seq[j] >= color1Element) {
          color1Element = seq[j];
        } else {
          right = false;
          break;
        }
      } else {
        if (seq[j] >= color2Element) {
          color2Element = seq[j];
        } else {
          right = false;
          break;
        }
      }
    }

    if (right) {
      return coloredSequence;
    }
  }

  return undefined;
}

function solve() {
  var length = parseInt(readline());
  var sequence = readline().getNumArray();
  var rightSequence = rightColoredSequence(coloredSequences(sequence), sequence);

  if (rightSequence === undefined) {
    write('-\n');
  } else {
    write(rightSequence.join('') + '\n');
  }
}

var n = readline().getNumArray()[0];

for (var i = 0; i < n; i++) {
  solve();
}

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

var main = function() {"use strict";
    // TODO
    var t = rdN();
    loop:while (t --> 0) {
        var n = rdN();
        var D = rdS().split('').map((v, i) => ({v: v, i: i})).sort((a,b) => {
            if (a.v != b.v) {
                return a.v - b.v;
            }
            return a.i - b.i;
        });
        //prOb(D)

        var res = crAr(n);
        var last = -1;
        var color = 1;
        for (var i = 0; i < n; ++i) {
            var value = D[i].v;
            var index = D[i].i;
            if (index > last) {
                res[index] = color;
                last = index;
            }
        }
        var last = -1;
        var color = 2;
        for (var i = 0; i < n; ++i) {
            var value = D[i].v;
            var index = D[i].i;
            if (res[index]) {
                continue;
            }

            if (index > last) {
                res[index] = color;
                last = index;
            } else {
                pr('-');
                continue loop;
            }
        }
        pr(res.join(''));
        //wr(123)
    }
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();


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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  if (c % 2 === 1) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  let prev = -1;
  const ans = [];

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
      ans.push(i + 1);
    }
    else {
      if (prev === -1) {
        prev = i + 1;
      }
      else {
        ans.push(prev);
        ans.push(i + 1);
        prev = -1;
      }
    }
  }

  if (ans.length === 0) {
    console.log(-1);
  }
  else {
    console.log(ans.length);
    console.log(ans.sort((a , b) => a - b).join(' '));
  }

  c++;
});

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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 output = [];
  for(var i = 0; i < t; i++){
    var n = nextInt();
    var list = nextIntArray();
    var odd = [];
    var even = [];
    for(var j = 0; j < n; j++){
      if(list[j] % 2 == 0){
        even.push(j + 1);
      }else{
        odd.push(j + 1);
      }
    }
    if(even.length >= 1){
      output.push(even.length);
      output.push(even.join(" "));
    }else if(odd.length >= 2){
      if(odd.length % 2 == 1){
        odd.pop();
      }
      output.push(odd.length);
      output.push(odd.join(" "));
    }else{
      output.push(-1);
    }
  }
  myout(myconv(output, 9));
}

const readline = require('readline');

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

let answer = "";

let lines = [];

rl.on('line', (t)=>{
    lines.push(t);
}).on('close', ()=>{
    let t = parseInt(lines[0]);

    for(let i = 0; i < t; i++){
        let n = parseInt(lines[i * 2 + 1]);
        let a = lines[i * 2 + 2].split(" ").map( function (x) {
            return parseInt(x);
        });
        if(a[0] % 2 === 0)
            answer += '1' + '\n' + '1' + '\n';
        else{
            if(n === 1) answer += '-1' + '\n';
            else {
                for(let j = 1; j < n; j++){
                    if(a[j] % 2 !== 0) {
                        answer += '2' + '\n' + '1 ' + (j + 1) + '\n';
                        break;
                    }
                    else{
                        answer += '1' + '\n' + (j + 1) + '\n';
                        break;
                    }
                }
            }
        }
    }

    console.log(answer);

});

const processData = (lines) => {
  const num = +lines[0]
  for (let j =0; j<num; j++) {
    const a = lines[j*2 + 2].split(' ').map(x => +x)
    let prev = null
    let found = false
    for (let k = 0; k<a.length; k++) {
      const n = a[k]
      if (n % 2 === 0) {
        found = true
        console.log(1)
        console.log(k+1)
        break
      }
      if (prev && (prev + n) % 2 === 0){
        found = true
        console.log(2)
        console.log(k, k+1)
        break
      }
      prev = n
    }
    if (!found) {
      console.log(-1)
    }
  }
}

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

const init = () => {
  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();
  });

  global.readline = () => {
    return inputString[currentLine++];
  }
};

if (typeof readline === 'undefined') {
  init();
}

const print = (...args) => {
  console.log(...args);
};

const main = () => {
  let t = parseInt(readline());
  while(t--) {
    const n = parseInt(readline());
    const a = readline().split(' ').map(x => parseInt(x));
    const evens = [];
    const odds = [];
    for (let i = 0; i < n; i++) {
      if (a[i] % 2 === 0) evens.push([a[i], i])
      if (a[i] % 2 === 1) odds.push([a[i], i])
    }
    if (evens.length > 0) {
      print(1);
      print(evens[0][1] + 1);
    } else if (odds.length >= 2) {
      print(2)
      print(odds.slice(0, 2).map(x => x[1] + 1).join(' '));
    } else {
      print(-1);
    }
  }
};

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var els = +readline();
    var arr = readNumArray();
    check(arr);
  }
}

function check(arr) {
  if (!arr.length || (arr.length === 1 && arr[0] % 2 === 1)) {
    print(-1);
    return;
  }
  for (var j = 0; j < 2; j++) {
    if (arr[j] % 2 === 0) {
      print(1);
      print(j + 1);
      return;
    } else if (j == 1) {
      print(2);
      print("1 2");
    }
  }
}

main()

function readStrs(){
    return readline().split(" ");
}
function readInts(){
    return readStrs().map(Number);
}
function main(){
    var t = +readline();
    while(t > 0){
        var n = 0 + readline();
        arr = readInts();

        var res = -1;
        var i;
        for(i=0; i<n; i++){
            if(arr[i]%2 === 0){
                res = i + 1;
                break;
            }
        }
        if(res == -1 && n >= 2){
            print("2\n1 2");
        }else if(res == -1){
            print(-1)
        }else{
            print("1\n" + res);
        }
        t = t - 1;
    }

}

main();

function main(raw) {
    var lines = raw.trim().split("\n").map(function (l) { return l.split(" ").map(function (u) { return parseInt(u, 10); }); });
    var t = lines.shift()[0];
    while (t > 0) {
        var n = lines.shift()[0];
        var a = lines.shift();
        var odds = [];
        var evn = [];
        var i = 0;
        while (odds.length < 2 && i < n && evn.length === 0) {
            if (a[i] % 2 === 1) {
                odds.push(i + 1);
            }
            else {
                evn.push(i + 1);
            }
            i++;
        }
        if (evn.length > 0) {
            console.log(1);
            console.log(evn[0]);
        }
        else if (odds.length < 2) {
            console.log("-1");
        }
        else {
            console.log(odds.length);
            console.log(odds.join(" "));
        }
        t--;
    }
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();


 var _t = readline();
    var t = parseInt(_t);

    for(var _=0;_<t;_++)
    {
        var Heap = readline().split(" ").map(function(x) { return parseInt(x); });
        var _Heap = Heap.slice();

        var count = 0;
        var _count;

       // print(Heap);
        while(Heap[2]-2>=0&&Heap[1]-1>=0)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
           // print(`1: ${Heap} ${_Heap}`)
        }
        while(Heap[1]-2>=0&&Heap[0]-1>=0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
           // print(`2: ${Heap}`)
        }
       // print(`${count}`)
        _count = count;
        count=0;
        Heap=_Heap;

        while(Heap[1]-2>=0&&Heap[0]-1>=0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
           // print(`3: ${Heap}`)
        }

        while(Heap[2]-2>=0&&Heap[1]-1>=0)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
           // print(`4: ${Heap}`)
        }
       // print(`${count}`)

        if(count<_count)count = _count;
        print (count);

    }

'use strict'

const problem = (a, b, c) => {
    if (c >= 2 * b) return 3 * b;
    b -= c / 2 | 0;
    if (b >= 2 * a) return 3 * (a + c / 2 | 0);
    return 3 * ((b / 2 | 0) + (c / 2 | 0));
}

const t = +readline();

for (let i = 0; i < t; i++) {
    const x = readline().split(' ').map(Number);
    print(problem(x[0], x[1], x[2]));
}

var queries = parseInt(readline());

function main(query) {
  var sum = 0;

  if (query[2] > (query[1].length * 2) - 1) {
      return write((3*query[1]) + '\n');
  } else {
    var add = Math.min(Math.floor(query[2]/2), query[1]);
    sum += add*3;
    query[1] -= add;
    if (query[1] > (query[0] * 2) - 1) {
      return write((3*query[0] + sum) + '\n');
    } else {
      return write (sum + (3 * Math.min(Math.floor(query[1]/2), query[0])) + '\n')
    }
  }
}

// main([1, 4, 2])

for (var i = 0; i < queries; i++) {
  var query = readline().split(' ').map(function(num) {
    return parseInt(num);
  })
  main(query)
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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 output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var count = 0;
    while(one[1] > 0 && one[2] > 1){
      one[1]--;
      one[2] -= 2;
      count += 3;
    }
    while(one[0] > 0 && one[1] > 1){
      one[0]--;
      one[1] -= 2;
      count += 3;
    }
    output[i] = count;
  }
  myout(myconv(output, 9));
}

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

rl.on('line', (d) => {
  if (count === 0) {
    count++;
    return;
  }

  let [a, b, c] = d.split(' ').map(Number);
  let ans = 0;

  while (b > 0 && c > 1) {
    b -= 1;
    c -= 2;

    ans += 3;
  }

  while (a > 0 && b > 1) {
    a -= 1;
    b -= 2;

    ans += 3;
  }

  console.log(ans);

  count++;
});

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', sol);

function sol() {
  const [[T], ...S] = input
    .split('\n')
    .map(line => line
      .split(' ')
      .map(Number));

  const result = [];

  for (let i = 0; i < T; ++i) {
    const [a, b, c] = S[i];
    let Y = Math.floor(c / 2);
    if (b < Y) Y = b;
    let X = Math.floor((b - Y) / 2);
    if (a < X) X = a;
    result.push(3 * (X + Y));
  }

  process.stdout.write(
    result.join('\n'),
    'utf8',
    () => process.stdout.end()
  );
}

'use strict'

const problem = (a, b, c) => {
    if (c >= 2 * b) return 3 * b;
    b -= c / 2 | 0;
    if (b >= 2 * a) return 3 * (a + c / 2 | 0);
    return 3 * ((b / 2 | 0) + (c / 2 | 0));
}

const t = +readline();

for (let i = 0; i < t; i++) {
    print(problem(+readline(), +readline(), +readline()));
}

var queries = parseInt(readline());

function main(query) {
  var sum = 0;

  if (query[2] > (query[1].length * 2) - 1) {
      return write((3*query[1]) + '\n');
  } else {
    var add = Math.min(Math.floor(query[2]/2), query[1]);
    sum += add*3;
    query[1] -= add;
    if (query[1] > (query[0] * 2) - 1) {
      return write((3*query[1] + sum) + '\n');
    } else {
      return write (sum + (3 * Math.min(Math.floor(query[1]/2), query[0])) + '\n')
    }
  }
}

// main([5, 3, 2])

for (var i = 0; i < queries; i++) {
  var query = readline().split(' ').map(function(num) {
    return parseInt(num);
  })
  main(query)
}

var queries = parseInt(readline());

function main(query) {
  var sum = 0;

  if (query[2] > (query[1].length * 2) - 1) {
      return write((3*query[1]) + '\n');
  } else {
    var add = Math.min(Math.floor(query[2]/2), query[1]);
    sum += add*3;
    query[1] -= add;
    if (query[1] > (query[0].length * 2) - 1) {
      return write((3*query[1] + sum) + '\n');
    } else {
      return write (sum + (3 * Math.floor(query[1]/2)) + '\n')
    }
  }
}

// main([5, 3, 2])

for (var i = 0; i < queries; i++) {
  var query = readline().split(' ').map(function(num) {
    return parseInt(num);
  })
  main(query)
}

   var t =readline().split("").map(function(x) { return parseInt(x); });

    for(var _=0;_<t[0];_++)
    {
        var Heap = readline().split(" ").map(function(x) { return parseInt(x); });

        var a=Heap[0];
        var b=Heap[1];
        var c =Heap[2];
        var count = 0;
        var comp=0;

            if(b>=Math.floor(c/2))
            {
                count+= 3*Math.floor(c/2);
                b=b-Math.floor(c/2);
                c=c-2*Math.floor(c/2);
            }

            if(a>=Math.floor(b/2))
            {
                count+= 3*Math.floor(b/2);
                a=a-Math.floor(b/2);
                b=b-2*Math.floor(b/2);

            }
            comp = count;
            a=Heap[0];
            b=Heap[1];
            c =Heap[2];
            count = 0;

            if(a>=Math.floor(b/2))
            {
                count+= 3*Math.floor(b/2);
                a=a-Math.floor(b/2);
                b=b-2*Math.floor(b/2);

            }

            if(b>=Math.floor(c/2))
            {
                count+= 3*Math.floor(c/2);
                b=b-Math.floor(c/2);
                c=c-2*Math.floor(c/2);

            }
            if(comp>count)count=comp;

        print(count);

    }

 var _t = readline();
    var t = parseInt(_t);

    for(var _=0;_<t;_++)
    {
        var Heap = readline().split(" ").map(function(x) { return parseInt(x); });
        var _Heap = Heap.slice();

        var count = 0;
        var _count;

        print(Heap);
        while(Heap[2]>1&&Heap[1]>0)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
            print(`1: ${Heap} ${_Heap}`)
        }
        while(Heap[1]>1&&Heap[0]>0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
            print(`2: ${Heap}`)
        }
        print(`${count}`)
        _count = count;
        count=0;
        Heap=_Heap;

        while(Heap[1]>1&&Heap[0]>0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
            print(`3: ${Heap}`)
        }

        while(Heap[2]>0&&Heap[1]>1)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
            print(`4: ${Heap}`)
        }
        print(`${count}`)

        if(count<_count)count = _count;
        print (count);

    }

 var t =readline().split("").map(function(x) { return parseInt(x); });

    for(var _=0;_<t[0];_++)
    {
        var Heap = readline().split(" ").map(function(x) { return parseInt(x); });

        var count = 0;

        while(Heap[2]>1&&Heap[1]>1)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
        }

        while(Heap[1]>1&&Heap[0]>1)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
        }

        print (count);

    }

 var _t = readline();
    var t = parseInt(_t);

    for(var _=0;_<t;_++)
    {
        var Heap = readline().split(" ").map(function(x) { return parseInt(x); });
        var _Heap = Heap.slice();

        var count = 0;
        var _count;

       // print(Heap);
        while(Heap[2]>1&&Heap[1]>0)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
           // print(`1: ${Heap} ${_Heap}`)
        }
        while(Heap[1]>1&&Heap[0]>0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
           // print(`2: ${Heap}`)
        }
       // print(`${count}`)
        _count = count;
        count=0;
        Heap=_Heap;

        while(Heap[1]>1&&Heap[0]>0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
          //  print(`3: ${Heap}`)
        }

        while(Heap[2]>0&&Heap[1]>1)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
          //  print(`4: ${Heap}`)
        }
       // print(`${count}`)

        if(count<_count)count = _count;
        print (count);

    }

    var _t = readline();
    var t = parseInt(_t);

    for(var _=0;_<t[0];_++)
    {
        var Heap = readline().split(" ").map(function(x) { return parseInt(x); });
        var _Heap = Heap.slice();

        var count = 0;
        var _count;

       // print(Heap);
        while(Heap[2]>1&&Heap[1]>0)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
          //  print(`1: ${Heap} ${_Heap}`)
        }
        while(Heap[1]>1&&Heap[0]>0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
            print(`2: ${Heap}`)
        }
        //print(`${count}`)
        _count = count;
        count=0;
        Heap=_Heap;

        while(Heap[1]>1&&Heap[0]>0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
           // print(`3: ${Heap}`)
        }

        while(Heap[2]>0&&Heap[1]>1)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
          //  print(`4: ${Heap}`)
        }
      //  print(`${count}`)

        if(count<_count)count = _count;
        print (count);

    }

var t =readline().split("").map(function(x) { return parseInt(x); });

    for(var _=0;_<t[0];_++)
    {
        var Heap = readline().split(" ").map(function(x) { return parseInt(x); });

        var a=Heap[0];
        var b=Heap[1];
        var c =Heap[2];
        var count = 0;

        if(a<b)
        {
            if(b>=Math.floor(c/2))
            {
                count+= 3*Math.floor(c/2);
                b=b-Math.floor(c/2);
                c=c-2*Math.floor(c/2);
            }

            if(a>=Math.floor(b/2))
            {
                count+= 3*Math.floor(b/2);
                a=a-Math.floor(b/2);
                b=b-2*Math.floor(b/2);

            }
        }
        else
        {
            if(a>=Math.floor(b/2))
            {
                count+= 3*Math.floor(b/2);
                a=a-Math.floor(b/2);
                b=b-2*Math.floor(b/2);

            }

            if(b>=Math.floor(c/2))
            {
                count+= 3*Math.floor(c/2);
                b=b-Math.floor(c/2);
                c=c-2*Math.floor(c/2);

            }

        }

        print(count);

    }

 var t =readline().split("").map(function(x) { return parseInt(x); });

    for(var _=0;_<t[0];_++)
    {
        var Heap = readline().split(" ").map(function(x) { return parseInt(x); });
        var _Heap = Heap.slice();

        var count = 0;
        var _count;

       // print(Heap);
        while(Heap[2]>1&&Heap[1]>0)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
           // print(`1: ${Heap} ${_Heap}`)
        }
        while(Heap[1]>1&&Heap[0]>0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
            //print(`2: ${Heap}`)
        }
        //print(`${count}`)
        _count = count;
        count=0;
        Heap=_Heap;

        while(Heap[1]>1&&Heap[0]>0)
        {
            count+=3;
            Heap[1]-=2;
            Heap[0]-=1;
            //print(`3: ${Heap}`)
        }

        while(Heap[2]>0&&Heap[1]>1)
        {
            count+=3;
            Heap[2]-=2;
            Heap[1]-=1;
           // print(`4: ${Heap}`)
        }
       // print(`${count}`)

        if(count<_count)count = _count;
        print (count);

    }