Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.

The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children.

Print "Yes" if the tree is a spruce and "No" otherwise.

NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:

'use strict';
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true,
            leafs: 0,
            parent: null};

for (var i = 1; i < tree.length; i++) {
    var parentIndex = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true,
                leafs: 0,
                parent: parentIndex};
    tree[parentIndex]["isLeaf"] = false;
    tree[parentIndex]["leafs"] += 1;
}

function isChristmasTree(tree) {
    for (var i = 0; i < tree.length; i++) {
    var leafs = 0;
        for (var j = 1 + i; j < tree.length; j++) {
            if (tree[j]["parent"] === i && tree[j]["isLeaf"])
                leafs += 1;
        }
        if (leafs < 3 && !tree[i].isLeaf)
            return "No";
    }
    return "Yes";
}

print(isChristmasTree(tree));

function isLeaf(node) {
    return Object.keys(node.children).length === 0;
}

// input
var n = parseInt(readline());

var nodes = new Array(n);
nodes[0] = {
    isLeaf: true,
    leaves: 0,
    parent: null
};

for (var i = 1; i < n; i++) {
    var parentIndex = parseInt(readline()) - 1;
    if (!nodes[i]) {
        // init current node
        nodes[i] = {
            isLeaf: true,
            leaves: 0,
            parent: parentIndex
        };
    }

    var currentNode = nodes[i];

    if (!nodes[parentIndex]) {
        // init parent node
        nodes[parentIndex] = {
            isLeaf: false,
            leaves: currentNode.isLeaf ? 1 : 0,
            parent: null
        };
    } else {
        // update parent node
        var parentNode = nodes[parentIndex];
        if (parentNode.isLeaf) {
            parentNode.isLeaf = false;
            var parentParentNode = nodes[parentNode.parent];
            if (parentParentNode) {
                parentParentNode.leaves = Math.max(0, parentParentNode.leaves - 1);
            }
        }

        if (currentNode.isLeaf) {
            parentNode.leaves++;
        }
    }
}

function isSpruce(tree) {
    for (var i = 0; i < n; i++) {
        var node = tree[i];
        if (!node.isLeaf && node.leaves < 3) {
            return 'No';
        }
    }
    return 'Yes';
}

print(isSpruce(nodes));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = new Array(n);

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

function esListom(verwuna) {
    return Object.keys(verwuna.children).length === 0;
}
koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = [n];

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

//function esListom(verwuna) {
  //  return Object.keys(verwuna.children).length === 0;
//}
koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = new Array(n);

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

function esListom(verwuna) {
    return Object.keys(verwuna.children).length === 0;
}
koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
function findRes(data) {
    for (var i = 0; i < n; i++) {
       verwuna = data[i];
       if (!verwuna.esListom && verwuna.listkov < 3) {
           return 'No';
       }
    }
    return 'Yes';
}

print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = [n];

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = [n];

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

function esListom(verwuna) {
    return Object.keys(verwuna.children).length === 0;
}
koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n = +readline();
//+prompt("Enter kol verwun");
var koli4estvoVerwun = [n];

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = +readline() - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n=Number(readline())
var N=new Array(n+1)
N[1]={c:[]}
for (var i=0;i<n-1;++i) {
 var p=Number(readline())
 N[i+2]={c:[]}
 N[p].c.push(N[i+2])
}
var check=i=>{
 var l=N[i].c.length;
 if (l) {
  var cc=0;
  for (var j=0;j<l;++j)
   cc += (!N[i].c[j].c.length)
  return cc>=3;
 } else return true;
}

var a=true;
for (var i=1;i<=n;++i)
 a = a && check(i)
print(a?'Yes':'No')

function isSpruce(tree) {
    for (var i = 0; i < tree.length; i++) {
    var leaf_children = 0;
        for (var j = 1 + i; j < tree.length; j++) if (tree[j]["parent"] === i && tree[j]["isLeaf"]) leaf_children += 1;
        if (leaf_children < 3 && !tree[i].isLeaf) return "No";
    }
    return "Yes";
}

var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < tree.length; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, leaf_children: 0, parent: parent_index};
    tree[parent_index]["isLeaf"] = false;
    tree[parent_index]["leaf_children"] += 1;
}

print(isSpruce(tree));

function isElka(tree) {
    for (var i = 0; i < tree.length; i++) {
    var children = 0;
        for (var j = 1 + i; j < tree.length; j++) if (tree[j]["parent"] === i && tree[j]["isLeaf"]) children += 1;
        if (children < 3 && !tree[i].isLeaf) return "No";
    }
    return "Yes";
}

var res = "Yes";
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < tree.length; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, leaf_children: 0, parent: parent_index};
    tree[parent_index]["isLeaf"] = false;
    tree[parent_index]["leaf_children"] += 1;
}

print(isElka(tree));

const
    verticesCount  = readline();
var
    vertices = [],
    isChristmassTree = true;
    vertices.push(0),
    levels = {},
    roots = [];
for (var i = 1; i < verticesCount; i++) {
    vertices.push(readline());
}

vertices.forEach((vert, i) => {
    if (!levels.hasOwnProperty(vert)) {
        levels[vert] = [];
    }
        levels[vert].push(i+1);

})

function checkLength(object) {
    for (var key in object) {
        if (key > 0) {
            if (object[key].length < 3) {
                isChristmassTree = false;
                break;
            }
            roots.push(key);
        }
    }
}

function checkRoots(roots) {
    roots.forEach(root => {
        for (var key in levels) {
            if (key > 0) {
               if (levels[key].includes(Number(root))) {
                  levels[key].splice(levels[key].indexOf(Number(root)), 1)
               }
            }
        }
    })
}

checkLength(levels)
if (isChristmassTree) {
checkRoots(roots)
checkLength(levels)
}

print(isChristmassTree ? 'Yes' : 'No')

var nodesAmount = readline();
var nodes = new Array(parseInt(nodesAmount) - 1);
var tree = new Array(parseInt(nodesAmount));

for (var i = 0; i < nodes.length; i++) {
    nodes[i] = readline() - 1;
}

for (var i = 0; i < tree.length; i++) {
    tree[i] = [];
}

nodes.forEach(function(node, i) {
    tree[node].push(i + 1);
});
var result = 'Yes';
testLevel(tree[0]);
print(result);

function testLevel(nodes) {
    var leaves = 0;
    nodes.forEach(function(node) {
        if (!tree[node][0]) leaves++;
    });
    if (leaves < 3) {
        result = 'No';
    } else {
        nodes.forEach(function(node) {
            if (tree[node][0]) {
                return testLevel(tree[node]);
            }
        });
    }
}

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

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

function main() {
  let len = +readLine();
  len = len - 1;
  let index = 2;
  const data = new Map();
  while (len--) {
    const n = +readLine();
    data.set(n, (data.get(n) || new Set()).add(index));
    index++;
  }

  for (let [key1, value1] of data) {
    for (let [key, value] of data) {
      if (value.has(key1)) value.delete(key1);
    }
  }

  for (let [key, value] of data) {
    if (value.size < 3) {
      console.log(`No`);
      return;
    }
  }
  console.log(`Yes`);
}

 'use strict';
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true,
            leafChildren: 0,
            leafParent: null};
var parentIndex = 0;
for (var i = 1; i < tree.length; i++) {
    parentIndex = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true,
                leafChildren: 0,
                parent: parentIndex};
    tree[parentIndex]["isLeaf"] = false;
    tree[parentIndex]["leafChildren"] += 1;
}

function isNewYearTree(tree) {
    var leafChildren = 0;
    for (var i = 0; i < tree.length; i++) {
        for (var j = i+1; j < tree.length; j++)
            if (tree[j]["parent"] === i && tree[j]["isLeaf"])
                    leafChildren += 1;
            if (leafChildren < 3 && !tree[i].isLeaf)
                    return "No";
    }
    return "Yes";
}

print(isNewYearTree(tree));

'use strict';
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true,
            leafChildren: 0,
            parent: null};
var parentIndex = 0;
for (var i = 1; i < tree.length; i++) {
    parentIndex = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true,
                leafChildren: 0,
                parent: parentIndex};
    tree[parentIndex]["isLeaf"] = false;
    tree[parentIndex]["leafChildren"] += 1;
}

function isNewYearTree(tree) {
    var leafChildren = 0;
    for (var i = 0; i < tree.length; i++) {
        for (var j = i+1; j < tree.length; j++)
            if (tree[j]["isLeaf"] && tree[j]["parent"] === i) {
                    leafChildren += 1;
            }
            if (!tree[i].isLeaf && leafChildren < 3) return "No";
    }
    return "Yes";
}

print(isNewYearTree(tree));

var number = parseInt(readline());
var tree = new Array(number);

tree[0] = { isLeaf: true, children: 0, parent: null};

for (var i = 1; i < number; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, children: 0, parent: parent_index};
    tree[parent_index]["children"] += 1;
    tree[parent_index]["isLeaf"] = false;
}

var res = "Yes";
for (var i = 0; i < tree.length; i++) {
    if (!tree[i].isLeaf && tree[i]["children"] < 3){
        res = "No";
    }
}

print(res);

var number = parseInt(readline());
var tree = new Array(number);

function reduceLeafChildNumber(tree, parent_index) {
    if (tree[parent_index]["parent"] !== null) {
        tree[tree[parent_index]["parent"]]["leaf_children"] -= 1;
        return reduceLeafChildNumber(tree, tree[parent_index]["parent"]);
    } else {
        return tree;
    }
}
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < number; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, children: 0, parent: parent_index};
    tree[parent_index]["leaf_children"] += 1;
    tree[parent_index]["isLeaf"] = false;

    tree = reduceLeafChildNumber(tree, parent_index);
}

var res = "Yes";
for (var i = 0; i < tree.length; i++) {
    if (!tree[i].isLeaf && tree[i]["leaf_children"] < 3){
        res = "No";
    }
}

print(res);

function reduceLeafChildNumber(tree, parent_index) {
    if (tree[parent_index]["parent"] !== null) {
        tree[tree[parent_index]["parent"]]["leaf_children"] -= 1;
        return reduceLeafChildNumber(tree, tree[parent_index]["parent"]);
    }
    return tree;
}

var res = "Yes";
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < tree.length; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, leaf_children: 0, parent: parent_index};
    tree[parent_index]["isLeaf"] = false;

    if (tree[parent_index]["leaf_children"] === 0) tree = reduceLeafChildNumber(tree, parent_index);
    tree[parent_index]["leaf_children"] += 1;
}

for (var i = 0; i < tree.length; i++)
    if (!tree[i].isLeaf && tree[i]["leaf_children"] < 3) res = "No";

print(res);

function reduceLeafChildNumber(tree, parent_index) {
    if (tree[parent_index]["parent"] !== null) {
        tree[tree[parent_index]["parent"]]["leaf_children"] -= 1;
        return reduceLeafChildNumber(tree, tree[parent_index]["parent"]);
    }
    return tree;
}

var res = "Yes";
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < tree.length; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, leaf_children: 0, parent: parent_index};
    tree[parent_index]["leaf_children"] += 1;
    tree[parent_index]["isLeaf"] = false;

    tree = reduceLeafChildNumber(tree, parent_index);
}

for (var i = 0; i < tree.length; i++) {
    if (!tree[i].isLeaf && tree[i]["leaf_children"] < 3){
        res = "No";
    }
}

print(res);

var nodesAmount = readline();
var nodes = new Array(parseInt(nodesAmount) - 1);
var tree = new Array(parseInt(nodesAmount));

for (var i = 0; i < nodes.length; i++) {
    nodes[i] = readline() - 1;
}

for (var i = 0; i < tree.length; i++) {
    tree[i] = [];
}

nodes.forEach(function(node, i) {
    tree[node].push(i + 1);
});

print(testLevel(tree[0]));

function testLevel(nodes) {

    if (!nodes[0]) {
        return true;
    }

    var leaves = 0;

    nodes.forEach(function(node) {
        if (!tree[node][0]) {
            leaves++;
        }
    });

    if (leaves < 3) {
        return 'No';
    }

    nodes.forEach(function(node) {
        testLevel(tree[node]);
    });

    return 'Yes'
}

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

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

function main() {
  let len = +readLine();
  len = len - 1;
  const data = [];
  while (len--) {
    const n = +readLine();
    data.push(n);
  }
  data.sort((a, b) => a - b);
  let [prev, prevCount] = [null, 0];

  for (let i = 0; i < data.length; i++) {
    const current = data[i];
    if (prev === current) {
      prevCount++;
    } else {
      if (prev !== null) {
        prevCount = prevCount - 1;
        if (prevCount < 3) {
          console.log(`No`);
          return;
        }
      }
      prev = current;
      prevCount = 1;
    }
  }
  console.log(`Yes`);
}


This is the easy version of this problem. The only difference is the constraint on $$$k$$$ — the number of gifts in the offer. In this version: $$$k=2$$$.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "$$$k$$$ of goods for the price of one" is held in store. Remember, that in this problem $$$k=2$$$.Using this offer, Vasya can buy exactly $$$k$$$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by $$$a_i$$$ — the number of coins it costs. Initially, Vasya has $$$p$$$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:  Vasya can buy one good with the index $$$i$$$ if he currently has enough coins (i.e $$$p \ge a_i$$$). After buying this good, the number of Vasya's coins will decrease by $$$a_i$$$, (i.e it becomes $$$p := p - a_i$$$).  Vasya can buy a good with the index $$$i$$$, and also choose exactly $$$k-1$$$ goods, the price of which does not exceed $$$a_i$$$, if he currently has enough coins (i.e $$$p \ge a_i$$$). Thus, he buys all these $$$k$$$ goods, and his number of coins decreases by $$$a_i$$$ (i.e it becomes $$$p := p - a_i$$$). Please note that each good can be bought no more than once.For example, if the store now has $$$n=5$$$ goods worth $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$, respectively, $$$k=2$$$, and Vasya has $$$6$$$ coins, then he can buy $$$3$$$ goods. A good with the index $$$1$$$ will be bought by Vasya without using the offer and he will pay $$$2$$$ coins. Goods with the indices $$$2$$$ and $$$3$$$ Vasya will buy using the offer and he will pay $$$4$$$ coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$t$$$ test cases.  The first line of each test case contains three integers $$$n, p, k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le p \le 2\cdot10^9$$$, $$$k=2$$$) — the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — the prices of goods. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$. It is guaranteed that in this version of the problem $$$k=2$$$ for all test cases.

For each test case in a separate line print one integer $$$m$$$ — the maximum number of goods that Vasya can buy.

'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 readALine() {
    return inputString[currentLine++];
}

function printALine(str) {
    console.log(str);
}

function stringArrayToNumbers(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( parseInt(array[i]) );
    }
    return result;
}

// ======================================================
// B1. K for the Price of One (Easy Version)
// https://codeforces.com/problemset/problem/1282/B1
// ======================================================

// n = number of goods in store.
// p = number of coins Vasya has.
// k = number of goods that can be bought by the price of the most expensive item.
// Note in this version, k = 2.
function doIt( n, p, k, priceArray ) {

    var arr = priceArray.sort(function(a,b){return a - b})

    //printALine( "n=" + n + " p=" + p + " k=" + k + " Array=" + arr);

    // This case, we try to buy everything as pairs and see how far we go.
    var numOfGoods1 = 0;
    var coin1 = p;

    for( var i = 1; i < arr.length; i+= 2 ) {

        var itemCost = arr[i];
        if( itemCost <= coin1 ) {
            numOfGoods1 += 2;
            coin1 -= itemCost;
            //printALine( "  -> a. num of goods: " + numOfGoods1 + " coins: " + coin1 );
        }
        else {
            break;
        }

    }

    // This case, we try to buy the first item, and then everything as pairs and see how far we go.
    var numOfGoods2 = 0;
    var coin2 = p;

    if( arr[0] <= coin2 ) {

        numOfGoods2 = 1;
        coin2 -= arr[0];

        //printALine( "  -> b1. num of goods: " + numOfGoods2 + " coins: " + coin2 );

        for( var i = 2; i < arr.length; i+= 2 ) {
            var itemCost = arr[i];
            //printALine("  -> Item cost: " + itemCost + " index: " + i + " Arr=" + arr);
            if( itemCost <= coin2 ) {
                numOfGoods2 += 2;
                coin2 -= itemCost;
                //printALine( "  -> b2. num of goods: " + numOfGoods2 + " coins: " + coin2 );
            }
            else {
                break;
            }
        }

    }

    //printALine("  Result 1: " + numOfGoods1 + " Result 2: " + numOfGoods2 );
    return Math.max(numOfGoods1, numOfGoods2);

}

function main() {

    var numOfTests = readALine();
    for( var i = 0; i < numOfTests; i++ ) {

        var string1 = readALine();
        var arr1 = stringArrayToNumbers(string1);

        var string2 = readALine();
        var arr2 = stringArrayToNumbers(string2);

        var result = doIt( arr1[0], arr1[1], arr1[2], arr2 );

        printALine(result);

    }

}

'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 readALine() {
    return inputString[currentLine++];
}

function printALine(str) {
    console.log(str);
}

function stringArrayToNumbers(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( parseInt(array[i]) );
    }
    return result;
}

// ======================================================
// B1. K for the Price of One (Easy Version)
// https://codeforces.com/problemset/problem/1282/B1
// ======================================================

// n = number of goods in store.
// p = number of coins Vasya has.
// k = number of goods that can be bought by the price of the most expensive item.
// Note in this version, k = 2.
function doIt( n, p, k, arr ) {

    arr.sort();

    // This case, we try to buy everything as pairs and see how far we go.
    var numOfGoods1 = 0;
    var coin1 = p;

    for( var i = 1; i < arr.length; i+= 2 ) {

        var itemCost = arr[i];
        if( itemCost <= coin1 ) {
            numOfGoods1 += 2;
            coin1 -= itemCost;
        }
        else {
            break;
        }

    }

    // This case, we try to buy the first item, and then everything as pairs and see how far we go.
    var numOfGoods2 = 0;
    var coin2 = p;

    if( arr[0] <= coin2 ) {

        numOfGoods2 ++;
        coin2 -= arr[0];

        for( var i = 2; i < arr.length; i+= 2 ) {
            var itemCost = arr[i];
            if( itemCost <= coin2 ) {
                numOfGoods2 += 2;
                coin2 -= itemCost;
            }
            else {
                break;
            }
        }

    }

    return Math.max(numOfGoods1, numOfGoods2);

}

function main() {

    var numOfTests = readALine();
    for( var i = 0; i < numOfTests; i++ ) {

        var string1 = readALine();
        var arr1 = stringArrayToNumbers(string1);

        var string2 = readALine();
        var arr2 = stringArrayToNumbers(string2);

        var result = doIt( arr1[0], arr1[1], arr1[2], arr2 );

        if( i == 139 ) {
            printALine( "n=" + arr1[0] + " p=" + arr1[1] + " k=" + arr1[2] + " Array=" + arr2 + " result=" + result);
        }
        else {
            printALine(result);
        }
    }

}

'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 readALine() {
    return inputString[currentLine++];
}

function printALine(str) {
    console.log(str);
}

function stringArrayToNumbers(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( parseInt(array[i]) );
    }
    return result;
}

// ======================================================
// B1. K for the Price of One (Easy Version)
// https://codeforces.com/problemset/problem/1282/B1
// ======================================================

// n = number of goods in store.
// p = number of coins Vasya has.
// k = number of goods that can be bought by the price of the most expensive item.
// Note in this version, k = 2.
function doIt( n, p, k, arr ) {

    arr.sort();

    // This case, we try to buy everything as pairs and see how far we go.
    var numOfGoods1 = 0;
    var coin1 = p;

    for( var i = 1; i < arr.length; i+= 2 ) {

        var itemCost = arr[i];
        if( itemCost <= coin1 ) {
            numOfGoods1 += 2;
            coin1 -= itemCost;
        }
        else {
            break;
        }

    }

    // This case, we try to buy the first item, and then everything as pairs and see how far we go.
    var numOfGoods2 = 0;
    var coin2 = p;

    if( arr[0] <= coin2 ) {

        numOfGoods2 ++;
        coin2 -= arr[0];

        for( var i = 2; i < arr.length; i+= 2 ) {
            var itemCost = arr[i];
            if( itemCost <= coin2 ) {
                numOfGoods2 += 2;
                coin2 -= itemCost;
            }
            else {
                break;
            }
        }

    }

    return Math.max(numOfGoods1, numOfGoods2);

}

function main() {

    var numOfTests = readALine();
    for( var i = 0; i < numOfTests; i++ ) {

        var string1 = readALine();
        var arr1 = stringArrayToNumbers(string1);

        var string2 = readALine();
        var arr2 = stringArrayToNumbers(string2);

        var result = doIt( arr1[0], arr1[1], arr1[2], arr2 );

        if( i == 138 ) {
            printALine( "n=" + arr1[0] + " p=" + arr1[1] + " k=" + arr1[2] + " Array=" + arr2 + " result=" + result);
        }
        else {
            printALine(result);
        }
    }

}

'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 readALine() {
    return inputString[currentLine++];
}

function printALine(str) {
    console.log(str);
}

function stringArrayToNumbers(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( parseInt(array[i]) );
    }
    return result;
}

// ======================================================
// B1. K for the Price of One (Easy Version)
// https://codeforces.com/problemset/problem/1282/B1
// ======================================================

// n = number of goods in store.
// p = number of coins Vasya has.
// k = number of goods that can be bought by the price of the most expensive item.
// Note in this version, k = 2.
function doIt( n, p, k, arr ) {

    arr.sort();

    // This case, we try to buy everything as pairs and see how far we go.
    var numOfGoods1 = 0;
    var coin1 = p;

    for( var i = 1; i < arr.length; i+= 2 ) {

        var itemCost = arr[i];
        if( itemCost <= coin1 ) {
            numOfGoods1 += 2;
            coin1 -= itemCost;
        }
        else {
            break;
        }

    }

    // This case, we try to buy the first item, and then everything as pairs and see how far we go.
    var numOfGoods2 = 0;
    var coin2 = p;

    if( arr[0] <= coin2 ) {

        numOfGoods2 ++;
        coin2 -= arr[0];

        for( var i = 2; i < arr.length; i+= 2 ) {
            var itemCost = arr[i];
            if( itemCost <= coin2 ) {
                numOfGoods2 += 2;
                coin2 -= itemCost;
            }
            else {
                break;
            }
        }

    }

    return Math.max(numOfGoods1, numOfGoods2);

}

function main() {

    var numOfTests = readALine();
    for( var i = 0; i < numOfTests; i++ ) {

        var string1 = readALine();
        var arr1 = stringArrayToNumbers(string1);

        var string2 = readALine();
        var arr2 = stringArrayToNumbers(string2);

        var result = doIt( arr1[0], arr1[1], arr1[2], arr2 );
        printALine(result);

    }

}


The winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day. Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these k days form a continuous segment of days.Before the first winter day Vasya still uses summer tires. It is possible to drive safely on summer tires any number of days when the average air temperature is non-negative. It is impossible to drive on summer tires at days when the average air temperature is negative. Vasya can change summer tires to winter tires and vice versa at the beginning of any day.Find the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.

The first line contains two positive integers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — the number of winter days and the number of days winter tires can be used. It is allowed to drive on winter tires at any temperature, but no more than k days in total. The second line contains a sequence of n integers t1, t2, ..., tn ( - 20 ≤ ti ≤ 20) — the average air temperature in the i-th winter day.

Print the minimum number of times Vasya has to change summer tires to winter tires and vice versa to drive safely during all winter. If it is impossible, print -1.

NoteIn the first example before the first winter day Vasya should change summer tires to winter tires, use it for three days, and then change winter tires to summer tires because he can drive safely with the winter tires for just three days. Thus, the total number of tires' changes equals two. In the second example before the first winter day Vasya should change summer tires to winter tires, and then after the first winter day change winter tires to summer tires. After the second day it is necessary to change summer tires to winter tires again, and after the third day it is necessary to change winter tires to summer tires. Thus, the total number of tires' changes equals four.

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 8
0 0 -1 0 0 -1 -1 -1 0 0 -1 0 -1 0 -1 -1 -1 0 0 0 -1
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, gapsConsumed, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentTire === 'winter') {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  if (winterRanges.length === 0) {
    print('0');
  } else {
    totalUsedTime = winterRanges.map(function(x) {
      return x[1] - x[0];
    }).reduce(function(a, b) {
      return a + b;
    });
    if (totalUsedTime > k) {
      print('-1');
    } else {
      gaps = [];
      for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
        range = winterRanges[i];
        if (i > 0) {
          gaps.push(range[0] - winterRanges[i - 1][1]);
        }
      }
      gaps.sort(function(a, b) {
        return a - b;
      });
      gapsConsumed = 0;
      for (m = 0, len2 = gaps.length; m < len2; m++) {
        gap = gaps[m];
        totalUsedTime += gap;
        if (totalUsedTime <= k) {
          gapsConsumed += 1;
          totalChanges -= 2;
        } else {
          totalUsedTime -= gap;
          break;
        }
      }
      finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
      if (totalUsedTime + finalGap <= k) {
        totalChanges -= 1;
      }
      print(totalChanges);
    }
  }

}).call(this);

"use strict";

function cmp (a, b) {
    if (a < b)
        return -1;
    if (a === b)
        return 0;
    return 1;
}

function solve(n, k, ts) {
    var negative = [];
    for (var i = 0; i < ts.length; i++)
        if (ts[i] < 0)
            negative.push(i);
    if (negative.length > k)
        return -1;
    if (negative.length === 0)
        return 0;
    k -= negative.length;
    var diffs = [];
    for (i = 1; i < negative.length; i++)
        if (negative[i] !== negative[i - 1] + 1)
            diffs.push(negative[i] - negative[i - 1] - 1);
    diffs.sort(cmp);
    i = 0;
    var segms = diffs.length + 1;
    while (i < diffs.length && diffs[i] <= k) {
        k -= diffs[i];
        i++;
        segms--;
    }
    var res = 2 * segms;
    if (k >= n - negative[negative.length - 1] - 1)
        res--;
    return res;
}

var line = readline().split(' ');
var n = parseInt(line[0]);
var k = parseInt(line[1]);
var ts = readline().split(' ').map(function(s) { return parseInt(s); });
print(solve(n, k, ts));

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 3
-5 20 -3 0
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    print(totalChanges);
  }

}).call(this);

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 8
0 0 -1 0 0 -1 -1 -1 0 0
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    if (totalChanges > 12000) {
      print('WINTER RANGES:', winterRanges.length);
      print('TOTAL USED TIME:', totalUsedTime);
      print('SOME GAPS:', gaps.slice(0, 10));
      print('FINAL GAP', finalGap);
    }
    print(totalChanges);
  }

}).call(this);

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 8
0 0 -1 0 0 -1 -1 -1 0 0 -1 0 -1 0 -1 -1 -1 0 0 0 -1
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, gapsConsumed, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentTire === 'winter') {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    gapsConsumed = 0;
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        gapsConsumed += 1;
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    if (totalChanges > 12000) {
      print('WINTER RANGES:', winterRanges.length);
      print('TOTAL USED TIME:', totalUsedTime);
      print('TOTAL NUMBER OF GAPS', gaps.length);
      print('GAPS CONSUMED:', gapsConsumed);
      print('FINAL GAP', gaps[gapsConsumed - 1], gaps[gapsConsumed], gaps[gapsConsumed + 1]);
      print('NUMBER OF 1-GAPS', gaps.filter(function(x) {
        return x === 1;
      }).length);
      print('SOME GAPS:', gaps.slice(0, 10));
      print('FINAL GAP', finalGap);
    }
    print(totalChanges);
  }

}).call(this);

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 3
-5 20 -3 0
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  gaps = [];

  for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
    range = winterRanges[i];
    if (i > 0) {
      gaps.push(range[0] - winterRanges[i - 1][1]);
    }
  }

  gaps.sort();

  for (m = 0, len2 = gaps.length; m < len2; m++) {
    gap = gaps[m];
    totalUsedTime += gap;
    if (totalUsedTime <= k) {
      totalChanges -= 2;
    } else {
      totalUsedTime -= gap;
      break;
    }
  }

  finalGap = temp.length - winterRanges[winterRanges.length - 1][1];

  if (totalUsedTime + finalGap <= k) {
    totalChanges -= 1;
  }

  print(totalChanges);

}).call(this);

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 8
0 0 -1 0 0 -1 -1 -1 0 0
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, gapsConsumed, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    gapsConsumed = 0;
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        gapsConsumed += 1;
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    if (totalChanges > 12000) {
      print('WINTER RANGES:', winterRanges.length);
      print('TOTAL USED TIME:', totalUsedTime);
      print('GAPS CONSUMED:', gapsConsumed);
      print('FINAL GAP', gaps[gapsConsumed - 1], gaps[gapsConsumed], gaps[gapsConsumed + 1]);
      print('SOME GAPS:', gaps.slice(0, 10));
      print('FINAL GAP', finalGap);
    }
    print(totalChanges);
  }

}).call(this);

// Generated by CoffeeScript 1.10.0
(function() {
  var currentRange, currentTire, finalGap, gap, gaps, i, j, k, l, len, len1, len2, lines, m, n, range, readline, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  lines = '4 8\n0 0 -1 0 0 -1 -1 -1 0 0'.split('\n');

  readline = function() {
    return lines.shift();
  };

  /*
  print = console.log
   */

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    if (totalChanges > 12000) {
      print('WINTER RANGES:', winterRanges.length);
      print('TOTAL USED TIME:', totalUsedTime);
      print('SOME GAPS:', gaps.slice(0, 10));
      print('FINAL GAP', finalGap);
    }
    print(totalChanges);
  }

}).call(this);


There are some beautiful girls in Arpa’s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that , where  is bitwise xor operation (see notes for explanation).  Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.

First line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the array and the integer x. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array.

Print a single integer: the answer to the problem.

NoteIn the first sample there is only one pair of i = 1 and j = 2.  so the answer is 1.In the second sample the only two pairs are i = 3, j = 4 (since ) and i = 1, j = 5 (since ).A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.

if (undefined == readline) {
	var fs = require('fs')
	var lines = fs.readFileSync('/dev/stdin', 'utf8').split("\n").reverse();
	var readline = function() {
		return lines.pop()
	}
}

if (undefined == print) {
	var print = console.log
}

var ints = function() {
	return readline().split(' ').map(function(n) {
		return parseInt(n)
	})
}

var numbers = ints(),
	x = numbers[1],
	counter = 0,
	temp = 0

numbers = ints().reduce(function(result, n) {
	if (undefined == result[n])
		result[n] = 0
	result[n] ++
	return result
}, {})

for (var n in numbers) {
	if (x == 0) {
		temp = numbers[n]
		if (temp > 1) {
			counter += (temp * (temp - 1)) / 2
		}
	} else {
		temp = numbers[n ^ x]
		if (undefined != temp)
			counter += temp * numbers[n]
		numbers[n] = undefined
	}
}

print(counter)

function sa(f, s){
        var x = Number(f.split(" ")[1]);
        var data = s.split(" ").map(Number);
        var arr = [];
        for(var i=0;i<=100000;i++){
            arr[i] = 0;
        }
        var res = 0;
        for(var i=0;i<data.length;i++){
            var result = data[i] ^ x;
            if(result<=100000){
                    res += arr[result];

            }
            arr[data[i]]++;
        }
        return res;
    }
    var f = readline();
    var s = readline();
    print(sa(f, s));

var ints = function() {
	return readline().split(' ').map(function(n) {
		return parseInt(n)
	})
}

var numbers = ints(),
	x = numbers[1],
	counter = 0,
	temp = 0

numbers = ints().reduce(function(result, n) {
	if (undefined == result[n])
		result[n] = 0
	result[n] ++
	return result
}, {})

for (var n in numbers) {
	temp = numbers[n ^ x]
	if (undefined != temp)
		counter += temp * numbers[n]
}

print(counter)

if (undefined == readline) {
	var fs = require('fs')
	var lines = fs.readFileSync('/dev/stdin', 'utf8').split("\n").reverse();
	var readline = function() {
		return lines.pop()
	}
}

if (undefined == print) {
	var print = console.log
}

var ints = function() {
	return readline().split(' ').map(function(n) {
		return parseInt(n)
	})
}

var numbers = ints(),
	x = numbers[1],
	counter = 0,
	temp = 0

numbers = ints().reduce(function(result, n) {
	if (undefined == result[n])
		result[n] = 0
	result[n] ++
	return result
}, {})

for (var n in numbers) {
	temp = numbers[n ^ x]
	if (undefined != temp)
		counter += temp * numbers[n]
	numbers[n] = undefined
}

print(counter)

function sa(f, s){
        var x = Number(f.split(" ")[1]);
        var data = s.split(" ").map(Number);
        var arr = [];
        for(var i=0;i<=100000;i++){
            arr[i] = 0;
        }
        for(var i=0;i<data.length;i++){
            arr[data[i]]++;
        }
        var res = 0;
        for(var i=0;i<=100000;i++){
            var result = i ^ x;
            if(result<=100000){
                if(result == i){
                        res += arr[result];
                } else {
                res += arr[result] * arr[i];
                }
            }
        }
        return res/2;
    }
    var f = readline();
    var s = readline();
    print(sa(f, s));

function sa(f, s){
        var x = Number(f.split(" ")[1]);
        var data = s.split(" ").map(Number);
        var arr = [];
        for(var i=0;i<=100000;i++){
            arr[i] = 0;
        }
        for(var i=0;i<data.length;i++){
            arr[data[i]]++;
        }
        var res = 0;
        for(var i=0;i<=100000;i++){
            var result = i ^ x;
            if(result<=100000){
                 if(result == 0){
if(arr[result] == 1){
continue;
}

if(arr[result] == 2){
res += arr[result];
continue;
}
res += arr[result] * 2;
continue;
}
                res += arr[result] * arr[i];
            }
        }
        return res/2;
    }
    var f = readline();
    var s = readline();
    print(sa(f, s));

function sa(f, s){
        var x = Number(f.split(" ")[1]);
        var data = s.split(" ").map(Number);
        var arr = [];
        for(var i=0;i<=100000;i++){
            arr[i] = 0;
        }
        for(var i=0;i<data.length;i++){
            arr[data[i]]++;
        }
        var res = 0;
        for(var i=0;i<data.length;i++){
            var result = data[i] ^ x;
            if(result<=100000){
                if(data[i] == result){
                    res += arr[data[i]] -1
                } else {
                    res += arr[data[i]] * arr[result];
                }
            }
        }
        return res/2;
    }
    var f = readline();
    var s = readline();
    print(sa(f, s));


Consider a system of n water taps all pouring water into the same container. The i-th water tap can be set to deliver any amount of water from 0 to ai ml per second (this amount may be a real number). The water delivered by i-th tap has temperature ti.If for every  you set i-th tap to deliver exactly xi ml of water per second, then the resulting temperature of water will be  (if , then to avoid division by zero we state that the resulting water temperature is 0).You have to set all the water taps in such a way that the resulting temperature is exactly T. What is the maximum amount of water you may get per second if its temperature has to be T?

The first line contains two integers n and T (1 ≤ n ≤ 200000, 1 ≤ T ≤ 106) — the number of water taps and the desired temperature of water, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) where ai is the maximum amount of water i-th tap can deliver per second. The third line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 106) — the temperature of water each tap delivers.

Print the maximum possible amount of water with temperature exactly T you can get per second (if it is impossible to obtain water with such temperature, then the answer is considered to be 0). Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6.

var T = readline().split(' ').map(Number)[1];
var capacityList = readline().split(' ').map(Number);
var tList = readline().split(' ').map(Number).map(d => d - T);
// The taps which provide higher t than T
const list1 = [];
// The taps which provide lower t than T
const list2 = [];
// The taps which provide same t as T
const list3 = [];
tList.forEach((d, i) => {
  if (d > 0) list1.push(i);
  if (d < 0) list2.push(i);
  if (d === 0) list3.push(i);
});

if ((list1.length === 0 || list2.length === 0) && (list3.length === 0)) {
  print(0);
} else {
  list1.sort((a, b) => tList[a] - tList[b]);
  list2.sort((a, b) => tList[b] - tList[a]);
  var max1 = list1.reduce((acc, d) => acc + tList[d] * capacityList[d], 0);
  var max2 = list2.reduce((acc, d) => acc - tList[d] * capacityList[d], 0);
  var cap1 = list1.reduce((acc, d) => acc + capacityList[d], 0);
  var cap2 = list2.reduce((acc, d) => acc + capacityList[d], 0);
  var cap3 = list3.reduce((acc, d) => acc + capacityList[d], 0);
  if (max1 > max2) {
    cap1 = 0;
    max1 = 0;
    var pointer = 0;
    while(true) {
      var index = list1[pointer];
      if ((max1 + capacityList[index] * tList[index]) < max2) {
        max1 += capacityList[index] * tList[index];
        cap1 += capacityList[index];
        pointer++;
      } else {
        cap1 += (max2 - max1) / tList[index];
        break;
      }
    }
  } else if (max1 < max2){
    cap2 = 0;
    max2 = 0;
    var pointer = 0;
    while(true) {
      var index = list2[pointer];
      if ((max2 - capacityList[index] * tList[index]) < max1) {
        max2 -= capacityList[index] * tList[index];
        cap2 += capacityList[index];
        pointer++;
      } else {
        cap2 += (max1 - max2) / (-tList[index]);
        break;
      }
    }
  }
  print(cap1 + cap2 + cap3);
}

var T = readline().split(' ').map(Number)[1];
var capacityList = readline().split(' ').map(Number);
var tList = readline().split(' ').map(Number).map(d => d - T);
// The taps which provide higher t than T
const list1 = [];
// The taps which provide lower t than T
const list2 = [];
// The taps which provide same t as T
const list3 = [];
tList.forEach((d, i) => {
  if (d > 0) list1.push(i);
  if (d < 0) list2.push(i);
  if (d === 0) list3.push(i);
});

if ((list1.length === 0 || list2.length === 0) && (list3.length === 0)) {
  print(0);
} else {
  list1.sort((a, b) => tList[a] - tList[b]);
  list2.sort((a, b) => tList[b] - tList[a]);
  var max1 = list1.reduce((acc, d) => acc + tList[d] * capacityList[d], 0);
  var max2 = list2.reduce((acc, d) => acc - tList[d] * capacityList[d], 0);
  var cap1 = list1.reduce((acc, d) => acc + capacityList[d], 0);
  var cap2 = list2.reduce((acc, d) => acc + capacityList[d], 0);
  var cap3 = list3.reduce((acc, d) => acc + capacityList[d], 0);
  if (max1 > max2) {
    cap1 = 0;
    max1 = 0;
    var pointer = 0;
    while(true) {
      var index = list1[pointer];
      if ((max1 + capacityList[index] * tList[index]) < max2) {
        max1 += capacityList[index] * tList[index];
        cap1 += capacityList[index];
        pointer++;
      } else {
        cap1 += (max2 - max1) / tList[index];
        break;
      }
    }
  } else if (max1 < max2){
    cap2 = 0;
    max2 = 0;
    var pointer = 0;
    while(true) {
      var index = list2[pointer];
      if ((max2 + capacityList[index] * tList[index]) < max1) {
        max2 -= capacityList[index] * tList[index];
        cap2 += capacityList[index];
        pointer++;
      } else {
        cap2 += (max1 - max2) / (-tList[index]);
        break;
      }
    }
  }
  print(cap1 + cap2 + cap3);
}

var T = readline().split(' ').map(Number)[1];
var capacityList = readline().split(' ').map(Number);
var tList = readline().split(' ').map(Number).map(d => d - T);
// The taps which provide higher t than T
const list1 = [];
// The taps which provide lower t than T
const list2 = [];
// The taps which provide same t as T
const list3 = [];
tList.forEach((d, i) => {
  if (d > 0) list1.push(i);
  if (d < 0) list2.push(i);
  if (d === 0) list3.push(i);
});

if ((list1.length === 0 || list2.length === 0) && (list3.length === 0)) {
  print(0);
} else {
  list1.sort((a, b) => tList[a] - tList[b]);
  list2.sort((a, b) => tList[b] - tList[a]);
  var max1 = list1.reduce((acc, d) => acc + tList[d] * capacityList[d], 0);
  var max2 = list2.reduce((acc, d) => acc - tList[d] * capacityList[d], 0);
  var cap1 = list1.reduce((acc, d) => acc + capacityList[d], 0);
  var cap2 = list2.reduce((acc, d) => acc + capacityList[d], 0);
  var cap3 = list3.reduce((acc, d) => acc + capacityList[d], 0);
  if (max1 > max2) {
    var counter = 0;
    cap1 = 0;
    max1 = 0;
    var pointer = 0;
    while(true) {
      var index = list1[pointer];
      if ((max1 + capacityList[index] * tList[index]) < max2) {
        max1 += capacityList[index] * tList[index];
        cap1 += capacityList[index];
        pointer++;
      } else {
        cap1 += (max2 - max1) / tList[index];
        break;
      }
    }
  } else if (max1 < max2){
    var counter = 0;
    cap2 = 0;
    max2 = 0;
    var pointer = 0;
    while(true) {
      var index = list2[pointer];
      if ((max2 + capacityList[index] * tList[index]) < max1) {
        max2 += capacityList[index] * tList[index];
        cap2 += capacityList[index];
        pointer++;
      } else {
        cap2 += (max1 - max2) / tList[index];
        break;
      }
    }
  }
  print(cap1 + cap2 + cap3);
}


Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.

The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph. The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.

If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph. In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.

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], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		numVertices = data[0], maxDegree = data[1],
		distanceCounts = {}, maxDistance = -1,
		levels = {};
	data = tokenizeIntegers(readline());
	for (var i = 0; i < numVertices; ++i) {
		var distance = data[i];
		if (distanceCounts[distance] === undefined) {
			distanceCounts[distance] = 0;
			maxDistance = Math.max(maxDistance, distance);
			levels[distance] = [];
		}
		distanceCounts[distance] += 1;
		levels[distance].push(i+1);
	}
	if (distanceCounts[0] != 1) {
		print(-1);
		return;
	}
	var lines = [numVertices-1];
	for (var d = 1, maxCount = maxDegree; d <= maxDistance; ++d) {
		var count = distanceCounts[d];
		if (count === undefined || count > maxCount) {
			print(-1);
			return;
		}
		maxCount = count * (maxDegree-1);
		var parents = levels[d-1], children = levels[d];
		var maxChildren = (d == 1 ? maxDegree : maxDegree-1);
		for (var i = 0; i < children.length; ++i) {
			lines.push(parents[Math.floor(i/maxChildren)]+' '+children[i]);
		}
	}
	print(lines.join('\n'));
}

main();

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], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		numVertices = data[0], maxDegree = data[1],
		distanceCounts = {}, maxDistance = -1,
		levels = {};
	data = tokenizeIntegers(readline());
	for (var i = 0; i < numVertices; ++i) {
		var distance = data[i];
		if (distanceCounts[distance] === undefined) {
			distanceCounts[distance] = 0;
			maxDistance = Math.max(maxDistance, distance);
			levels[distance] = [];
		}
		distanceCounts[distance] += 1;
		levels[distance].push(i+1);
	}
	if (distanceCounts[0] != 1) {
		print(-1);
		return;
	}
	print(numVertices-1);
	for (var d = 1, maxCount = maxDegree; d <= maxDistance; ++d) {
		var count = distanceCounts[d];
		if (count === undefined || count > maxCount) {
			print(-1);
			return;
		}
		maxCount = count * (maxDegree-1);
		var parents = levels[d-1], children = levels[d];
		for (var i = 0; i < children.length; ++i) {
			print(parents[Math.floor(i/maxDegree)], children[i]);
		}
	}
}

main();

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], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		numVertices = data[0], maxDegree = data[1],
		distanceCounts = {}, maxDistance = -1,
		levels = {};
	data = tokenizeIntegers(readline());
	for (var i = 0; i < numVertices; ++i) {
		var distance = data[i];
		if (distanceCounts[distance] === undefined) {
			distanceCounts[distance] = 0;
			maxDistance = Math.max(maxDistance, distance);
			levels[distance] = [];
		}
		distanceCounts[distance] += 1;
		levels[distance].push(i+1);
	}
	if (distanceCounts[0] != 1) {
		print(-1);
		return;
	}
	print(numVertices-1);
	for (var d = 1, maxCount = maxDegree; d <= maxDistance; ++d) {
		var count = distanceCounts[d];
		if (count === undefined || count > maxCount) {
			print(-1);
			return;
		}
		maxCount = count * (maxDegree-1);
		var parents = levels[d-1], children = levels[d];
		var maxChildren = (d == 1 ? maxDegree : maxDegree-1);
		for (var i = 0; i < children.length; ++i) {
			print(parents[Math.floor(i/maxChildren)], children[i]);
		}
	}
}

main();

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], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		numVertices = data[0], maxDegree = data[1],
		distanceCounts = {}, maxDistance = -1,
		levels = {};
	data = tokenizeIntegers(readline());
	for (var i = 0; i < numVertices; ++i) {
		var distance = data[i];
		if (distanceCounts[distance] === undefined) {
			distanceCounts[distance] = 0;
			maxDistance = Math.max(maxDistance, distance);
			levels[distance] = [];
		}
		distanceCounts[distance] += 1;
		levels[distance].push(i+1);
	}
	if (distanceCounts[0] != 1) {
		print(-1);
		return;
	}
	print(numVertices-1);
	for (var d = 1, maxCount = maxDegree; d <= maxDistance; ++d) {
		var count = distanceCounts[d];
		if (count === undefined || count > maxCount) {
			print(-1);
			return;
		}
		maxCount = count * (maxDegree-1);
		var parents = levels[d-1], children = levels[d];
		for (var i = 0; i < children.length; ++i) {
			var maxChildren = (d == 1 ? maxDegree : maxDegree-1);
			print(parents[Math.floor(i/maxChildren)], children[i]);
		}
	}
}

main();

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], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		numVertices = data[0], maxDegree = data[1],
		distanceCounts = {}, maxDistance = -1,
		levels = {};
	data = tokenizeIntegers(readline());
	for (var i = 0; i < numVertices; ++i) {
		var distance = data[i];
		if (distanceCounts[distance] === undefined) {
			distanceCounts[distance] = 0;
			maxDistance = Math.max(maxDistance, distance);
			levels[distance] = [];
		}
		distanceCounts[distance] += 1;
		levels[distance].push(i+1);
	}
	if (distanceCounts[0] != 1) {
		print(-1);
		return;
	}
	print(numVertices-1);
	for (var d = 1, maxCount = maxDegree; d <= maxDistance; ++d) {
		var count = distanceCounts[d];
		if (count === undefined || count > maxCount) {
			print(-1);
			return;
		}
		maxCount = count * maxChildren;
		var parents = levels[d-1], children = levels[d];
		for (var i = 0; i < children.length; ++i) {
			var maxChildren = (d == 1 ? maxDegree : maxDegree-1);
			print(parents[Math.floor(i/maxChildren)], children[i]);
		}
	}
}

main();


The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

The first line contains integer n (1 ≤ n ≤ 105) — the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 — the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.

Print "YES" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print "NO".

var N = parseInt(readline());
function f(){var arr = readline().split(" ");

var clerk25 = 0, clerk50 = 0;
for (var i = 0; i < N; i++)
{
    var cur = arr[i];
    if (cur == 25) clerk25++;
    else
    {
        if (cur == 50)
        {clerk50++;
            if (clerk25 > 0) clerk25--;
            else {print("NO");  return false;}
        }
        if (cur == 100)
        {
            if ((clerk25 > 0 && clerk50>0))
            {
                clerk25--; clerk50--;
            }
            else if (clerk25>2) clerk25-=3;
            else {print("NO"); return false;}
        }
    }
}
print("YES");

}

f();

// 349A     Очередь в кино

/*
function main_1(){
    var n = parseInt(readline());
    var ans = 0;
    while (n--) {
        var nums = readline().split(' ').map(Number);
        ans += (nums[2] - nums[0] + 1) * (nums[3] - nums[1] + 1);
    }
    print(ans);
}

function main(){
    var line  = readline();
    //var line = prompt();
    var n = line.length;
    //alert(line);
    var m = 0;
    for(i=0;i<n;i+=2){
        for(j=i+1;j<n;j+=2){
            var ex = [line.slice(0, i), '(', line.slice(i,j) , ')' , line.slice(j)].join('');
            m = Math.max(m,eval(ex));
        }
    }
    print(m);
}
*/

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var arr = readline().split(' ').map(Number);

var summa25 = 0;
var summa50 = 0;
var out = '';
var x;

top:
for (var i = 0; i < arr.length; i++) {

    switch (arr[i]) {
        case 25:
            summa25 += 25;
            break;
        case 50:
            if (summa25 >= 25) {
                summa25 -= 25;
                summa50 += 50;
                break;
            } else {
                out = 'NO';
                break top;
            };
        case 100:
            x = 75;
            if (summa50 >= 50) {
                summa50 -= 50;
                x = 25;
            }
            if (summa25 >= x) {
                summa25 -= x;
                break;
            } else {
                out = 'NO';
                break top;
            };
    }

};

if (out === '') out = 'YES';

print(out);

var n = +readline(), a = readline().split(" ").map(Number);
var written = false,
notes = {
	25: 0,
	50: 0,
	100: 0
};

a.forEach(function(note, i){
	notes[note]++;

	if(note == 50){
		notes[25]--;
		if(notes[25] < 0){
			if(!written){
				print("NO");
				written = true;
			}
		}
	}

	if(note == 100){
		if(notes[50] > 0){
			notes[50]--;
			notes[25]--;
			if(notes[25] < 0){
				if(!written){
					print("NO");
					written = true;
				}
			}
		}
		else{
			notes[25] -= 3;
			if(notes[25] < 0){
				if(!written){
					print("NO");
					written = true;
				}
			}
		}
	}
});

if(!written){
	print("YES");
}

var arrLen = readline().split(' ').map(Number);
var Arr = readline().split(' ').map(Number);
var arrM = [0, 0, 0];
var counter = 0;
for (var i=0; i<arrLen; i++) {
    if (Arr[i] == 25) {
        arrM[0] += 1;
        counter += 1;
    }
    if (Arr[i] == 50) {
        arrM[1] += 1;
        arrM[0] -= 1;
        if (arrM[0] < 0) {
            break;
        }
        counter += 1;
    }
    if (Arr[i] == 100) {
        if (arrM[1] == 0) {
            arrM[2] += 1;
            arrM[0] -= 3;
        }
        else {
            arrM[2] += 1;
            arrM[1] -= 1;
            arrM[0] -= 1;
        }
        if (arrM[0] < 0 || arrM[1] < 0) {
            break;
        }
        counter += 1;
    }
}
if (counter == arrLen) {
print("YES");
}
else {
print("NO");
}

var m = [0,0,0];
var n;
var buff = new Array();
function read() {
	return readline().split(' ').map(Number);
}
function main() {
	n=read();
	buff=read();
	for (var i=0; i<n; i++) {
		switch(buff[i]) {
			case 25:
				m[0]++;
				break;
			case 50:
				m[1]++;
				if (m[0]>0) m[0]--;
				else {
					print("NO");
					return;
				}
				break;
			case 100:
				m[2]++;
				if (m[1]>0 && m[0]>0) m[1]--,m[0]--;
				else if (m[0]>=3) m[0]-=3;
				else {
					print("NO");
					return;
				}
				break;
		}
	}
	print("YES");
}
main();

;(function () {

	var l25 = 0,
		l50 = 0;

	var n = +readline();
	var s = readline().split(' ');

	for (var i = 0; i < n; i++)
		switch (s[i]) {
			case '25':
				l25++;
				break;

			case '50':
				if (l25) {
					l25--;
					l50++;
				} else {
					print('NO');
					return;
				}
				break;

			case '100':
				if (l50 && l25) {
					l25--;
					l50--;
				} else if (l25 > 2) {
					l25 -= 3;
				} else {
					print('NO');
					return;
				}
				break;
		}
	print('YES');

}).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], 10);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline()),
		bills = tokenizeIntegers(readline()),
		cash = { 25: 0, 50: 0, 100: 0 };
	for (var i = 0; i < n; ++i) {
		var bill = bills[i];
		if (bill == 25) {
			cash[25] += 1;
		} else if (bill == 50 && cash[25] != 0) {
			cash[50] += 1;
			cash[25] -= 1;
		} else if (bill == 100 && cash[25] != 0 && cash[50] != 0) {
			cash[100] += 1;
			cash[25] -= 1;
			cash[50] -= 1;
		} else if (bill == 100 && cash[25] >= 3) {
			cash[100] += 1;
			cash[25] -= 3;
		} else {
			print('NO');
			return;
		}
	}
	print('YES');
}

main();

const fs = require('fs')

const readStdin = () => {
  return new Promise((resolve, reject) => {
    fs.readFile(0, (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data.toString())
      }
    })
  })
}

async function main () {
  const str = await readStdin()
  const lines = str.split('\n')
  const n = parseInt(lines[0])
  const bills = lines[1].split(' ').map(token => parseInt(token))

  let _25 = 0
  let _50 = 0
  let could = true

  bills.forEach((bill) => {
    if (bill === 25) {
      _25++
    } else if (bill === 50) {
      _50++
      if (_25 === 0) {
        could = false
      } else {
        _25--
      }
    } else {
      if (_50 > 0) {
        _50--
        if (_25 === 0) {
          could = false
        } else {
          _25--
        }
      } else if (_25 >= 3) {
        _25 -= 3
      } else {
        could = false
      }
    }
  })

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

main().then(() => {})

var N = parseInt(readline());
function f(){var arr = readline().split(" ");

var clerk25 = 0, clerk50 = 0;
for (var i = 0; i < N; i++)
{
    var cur = arr[i];
    if (cur == 25) clerk25++;
    else
    {
        if (cur == 50)
        {
            if (clerk25 > 0) clerk25--;
            else {print("NO");  return false;}
        }
        if (cur == 100)
        {
            if ((clerk25 > 0 && clerk50>0))
            {
                clerk25--; clerk50--;
            }
            else if (clerk25>2) clerk25-=3;
            else {print("NO"); return false;}
        }
    }
}
print("YES");

}

f();

var n =  readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass>0){
				cass -= (+str[i]-25);
				cass += +str[i];
				}
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass-(+str[i]-25)>=0){
				cass += +str[i];
				cass -= +str[i]-25;}
			else {r=0; break;}
			if (cass<0) break;
		}
		r==1? print("YES"):print("NO");

var n =  readline();
var str =  readline().split(" ");
var r = 1;
var cass = 0;
		for (var i = 0; i<+n; i++){
				if (+str[i]==25){
					cass+=25;
				}
				else if(+str[i]>25)  cass = cass-(+str[i]-25);
				else if (cass<0) break;
		}
		r==1&&cass>=0? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else {
				cass += +str[i];
				cass -= +str[i]-25;}
			if (cass<0) break;
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else {
				cass -= +str[i]-25;
				if (cass<0) { r=0; break;}
				cass += +str[i];}

		}
		r==1? print("YES"):print("NO");

var n =  readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if ((+str[i]-25)<=cass&&cass>0){
				cass -= (+str[i]-25);
				cass += +str[i];
				}
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n = readline();
var str = readline().split(" ");
var r = 1;
var cass = 0;
	for (var i = 0; i<+n; i++){
		if (str[i]>25&cass>0)
		cass = cass-(+str[i]-25);
		else if (+str[i]==25) cass+=25;
		else {r=0; break;}

	}
	r==1? print("YES"):print("NO");

var n = readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (+str[i]==50){
				cass -=25;
				if (cass<0) { r=0; break;}
				cass +=50;
				}
			else if (+str[i]==100){
				cass -=75;
			    if (cass<0) { r=0; break;}
			}
		//	if (cass<0) { r=0; break;}

		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else
				cass += cass-(+str[i]-25);
			if (cass<0) {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =  readline();
var str =  readline().split(" ");
var r = 1;
var cass = 0;
		for (var i = 0; i<+n; i++){
				if (+str[i]==25){
					cass+=25;
				}
				else cass = cass-(+str[i]-25);

		}
		r==1&&cass>=0? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if ((+str[i]-25)<=cass){
			cass += cass-(+str[i]-25);
				}
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass-(+str[i]-25)>=0&&cass>0)
				cass += cass-(+str[i]-25);
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =  readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if ((+str[i]-25)<=cass){
				 var t = (+str[i]-25);
			     cass+= +str[i]-t;
				}
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass>0)
				cass += cass-(+str[i]-25);
			if (cass<0) {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n = readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (+str[i]==50){
				cass -=25;
				if (cass<0) { r=0; break;}
				cass +=50;
				}
			else if (+str[i]==100){
				cass -=75;
			    if (cass<0) { r=0; break;}
				cass += 100;
			}
		//	if (cass<0) { r=0; break;}

		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else {
				cass -= +str[i]-25;}
				if (cass<0) break;
				cass += +str[i];

		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass+Number(str[i])-(+str[i]-25)>0&&cass>0)
				cass = cass+Number(str[i])-(+str[i]-25);
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass-(+str[i]-25)>0&&cass>0)
				cass += cass-(+str[i]-25);
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else {
				cass -= +str[i]-25;}
				if (cass<0) {break; r=0;}
				cass += +str[i];

		}
		r==1? print("YES"):print("NO");

// 349A     Очередь в кино

/*
function main_1(){
    var n = parseInt(readline());
    var ans = 0;
    while (n--) {
        var nums = readline().split(' ').map(Number);
        ans += (nums[2] - nums[0] + 1) * (nums[3] - nums[1] + 1);
    }
    print(ans);
}

function main(){
    var line  = readline();
    //var line = prompt();
    var n = line.length;
    //alert(line);
    var m = 0;
    for(i=0;i<n;i+=2){
        for(j=i+1;j<n;j+=2){
            var ex = [line.slice(0, i), '(', line.slice(i,j) , ')' , line.slice(j)].join('');
            m = Math.max(m,eval(ex));
        }
    }
    print(m);
}
*/

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var arr = readline().split(' ').map(Number);

var summa25 = 0;
var summa50 = 0;
var out = '';
var x;

top:
for (var i = 0; i < arr.length; i++) {

    switch (arr[i]) {
        case 25:
            summa25 += 25;
            break;
        case 50:
            if (summa25 >= 25) {
                summa25 -= 25;
                summa50 += 50;
                break;
            } else {
                out = 'NO';
                break top;
            };
        case 100:
            x = 100;
            if (summa50 >= 50) {
                summa50 -= 50;
                x = 50;
            }
            if (summa25 >= x) {
                    summa25 -= x;
                    break;
            } else {
                out = 'NO';
                break top;
            };
    }

};

if (out === '') out = 'YES';

print(out);

// 349A     Очередь в кино

/*
function main_1(){
    var n = parseInt(readline());
    var ans = 0;
    while (n--) {
        var nums = readline().split(' ').map(Number);
        ans += (nums[2] - nums[0] + 1) * (nums[3] - nums[1] + 1);
    }
    print(ans);
}

function main(){
    var line  = readline();
    //var line = prompt();
    var n = line.length;
    //alert(line);
    var m = 0;
    for(i=0;i<n;i+=2){
        for(j=i+1;j<n;j+=2){
            var ex = [line.slice(0, i), '(', line.slice(i,j) , ')' , line.slice(j)].join('');
            m = Math.max(m,eval(ex));
        }
    }
    print(m);
}
*/

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var arr = readline().split(' ').map(Number);

var summa25 = 0;
var summa50 = 0;
var summa100 = 0;
var out = '';

top:
for (var i = 0; i < arr.length; i++) {
    arr[i]
    switch (arr[i]) {
        case 25:
            summa25 += 25;
            break;
        case 50:
            if (summa25 > 25) {
                summa25 -= 25;
                summa50 += 50;
                break;
            } else {
                out = 'NO';
                break top;
            };
        case 100:
            if (summa50 > 50) {
                summa50 -= 50;
                summa100 += 100;
                break;
            } else {
                if (summa25 > 50) {
                    summa25 -= 50;
                    summa100 += 100;
                    break;
                } else {
                    out = 'NO';
                    break top;
                }
            };
    }

};

if (out === '') out = 'YES';

print(out);

// 349A     Очередь в кино

/*
function main_1(){
    var n = parseInt(readline());
    var ans = 0;
    while (n--) {
        var nums = readline().split(' ').map(Number);
        ans += (nums[2] - nums[0] + 1) * (nums[3] - nums[1] + 1);
    }
    print(ans);
}

function main(){
    var line  = readline();
    //var line = prompt();
    var n = line.length;
    //alert(line);
    var m = 0;
    for(i=0;i<n;i+=2){
        for(j=i+1;j<n;j+=2){
            var ex = [line.slice(0, i), '(', line.slice(i,j) , ')' , line.slice(j)].join('');
            m = Math.max(m,eval(ex));
        }
    }
    print(m);
}
*/

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var arr = readline().split(' ').map(Number);

var summa25 = 0;
var summa50 = 0;
var summa100 = 0;
var out = '';

top:
for (var i = 0; i < arr.length; i++) {
    arr[i]
    switch (arr[i]) {
        case 25:
            summa25 += 25;
            break;
        case 50:
            if (summa25 >= 25) {
                summa25 -= 25;
                summa50 += 50;
                break;
            } else {
                out = 'NO';
                break top;
            };
        case 100:
            if (summa50 >= 50) {
                summa50 -= 50;
                summa100 += 100;
                break;
            } else {
                if (summa25 >= 50) {
                    summa25 -= 50;
                    summa100 += 100;
                    break;
                } else {
                    out = 'NO';
                    break top;
                }
            };
    }

};

if (out === '') out = 'YES';

print(out);

var arrLen = readline().split(' ').map(Number);
var Arr = readline().split(' ').map(Number);
var arrM = [0, 0, 0];
var counter = 0;
for (var i=0; i<arrLen; i++) {
    if (Arr[i] == 25) {
        arrM[0] += 1;
        counter += 1;
    }
    if (Arr[i] == 50) {
        arrM[1] += 1;
        arrM[0] -= 1;
        if (arrM[0] < 0) {
            break;
        }
        counter += 1;
    }
    if (Arr[i] == 100) {
        arrM[2] += 1;
        arrM[1] -= 1;
        arrM[0] -= 1;
        if (arrM[0] < 0 || arrM[1] < 0) {
            break;
        }
        counter += 1;
    }
}
if (counter == arrLen) {
print("YES");
}
else {
print("NO");
}

;(function () {

readline();

var m = readline().split(' ').map(Number);

var t = 0;

for (var i = 0; i < m.length; i++)
 if (m[i] == 25) t++;
 else {
  if (m[i] == 50 && t > 0) t--;
  else if (m[i] == 100 && t > 1) t -= 2;
  else {
   print('NO');
   return;
  }
 }

print('YES');

}).call(this);

const fs = require('fs')

const readStdin = () => {
  return new Promise((resolve, reject) => {
    fs.readFile(0, (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data.toString())
      }
    })
  })
}

async function main () {
  const str = await readStdin()
  const lines = str.split('\n')
  const n = parseInt(lines[0])
  const bills = lines[1].split(' ').map(token => parseInt(token))

  let _25 = 0
  let _50 = 0
  let could = true

  bills.forEach((bill) => {
    if (bill === 25) {
      _25++
    } else if (bill === 50) {
      _50++
      if (_25 === 0) {
        could = false
        _25--
      }
    } else {
      if (_50 > 0) {
        _50--
        if (_25 === 0) {
          could = false
          _25--
        }
      } else if (_25 === 3) {
        _25 -= 3
      } else {
        could = false
      }
    }
  })

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

main().then(() => {})

const fs = require('fs')

const readStdin = () => {
  return new Promise((resolve, reject) => {
    fs.readFile(0, (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data.toString())
      }
    })
  })
}

async function main () {
  const str = await readStdin()
  const lines = str.split('\n')
  const n = parseInt(lines[0])
  const bills = lines[1].split(' ').map(token => parseInt(token))

  let _25 = 0
  let _50 = 0
  let could = true

  bills.forEach((bill) => {
    if (bill === 25) {
      _25++
    } else if (bill === 50) {
      _50++
      if (_25 === 0) {
        could = false
      } else {
        _25--
      }
    } else {
      if (_50 > 0) {
        _50--
        if (_25 === 0) {
          could = false
          _25--
        }
      } else if (_25 === 3) {
        _25 -= 3
      } else {
        could = false
      }
    }
  })

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

main().then(() => {})