Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.

Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.

NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.

var n = +readline();
var ai = {};
var bi = {};
var same = 0;

for(var i = 0; i < n; i++) {
    var size = readline();
    ai[size] = ai[size] + 1 || 1;
}

for(var i = 0; i < n; i++) {
    var size = readline();
    bi[size] = bi[size] + 1 || 1;
}

for(var prop in ai) {
    same += Math.min(ai[prop] || 0 , bi[prop] || 0);
}

print(n - same);

var n = +readline();
var ai = [];
var bi = [];
var seconds = 0;

for (var i = 0; i < n; i++) {
    ai.push(readline());
}
for (var i = 0; i < n; i++) {
    bi.push(readline());
}

// Sort the arrays
ai.sort((a, b) => (a < b ? -1 : 1));
bi.sort((a, b) => (a < b ? -1 : 1));

for(var i = 0; i < n; i++) {
    if(ai[i] !== bi[i]) {
        seconds++;
    }
}

print(seconds);


Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 ≤ i ≤ n) can create either ai units of matter or ai units of antimatter. Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo). You are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.

The first line contains an integer n (1 ≤ n ≤ 1000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). The sum a1 + a2 + ... + an will be less than or equal to 10000.

Output a single integer, the number of ways Iahub can take a photo, modulo 1000000007 (109 + 7).

var maxn = 1e3 + 5;
var maxs = 1e4 + 5;
var mod = 1e9 + 7;
var n  = parseInt(readline());
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var dp = new Array(maxn).fill(0).map(() => new Array(2* maxs + 5).fill(0));
for(var i = 1; i < n+1; ++i)
{
    for(var s = -1 * maxs; s <= maxs; ++s)
    {
        if((a[i-1]*a[i-1] == s*s))
        {
            dp[i][s+maxs] = 1;
        }
        if(s-a[i-1]>=-maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs-a[i-1]];
        }
        if(s+a[i-1]<=maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i-1]];
        }
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    res += dp[i][maxs];
    res %= mod;
}
print(res);

const maxn = 1e3 + 5;
const maxs = 1e4 + 5;
const mod = 1e9 + 7;
var n  = parseInt(readline());
var a = [0] + readline().split(" ").map(function(x) { return parseInt(x); });
var dp = new Array(maxn).fill(0).map(() => new Array(maxs).fill(0));
print(n)
for(var i = 0; i < maxn; ++i)
{
    for(var s = 0; s < 2 * maxs; ++s)
    {
        dp[i][s] = 0;
    }
}
for(var i = 1; i < n+1; ++i)
{
    for(var s = -maxs; s <= maxs; ++s)
    {
        dp[i][s+maxs] = (a[i]*a[i] == s*s)?1:0;
        if(s-a[i]>=-maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs-a[i]];
        }
        if(s+a[i]<=maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i]];
        }
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    print(res);
    res += dp[i][maxs];
    res %= mod;
}
print(res);

const maxn = 1e3 + 5;
const maxs = 1e4 + 5;
const mod = 1e9 + 7;
var n  = parseInt(readline());
var a = [0] + readline().split(" ").map(function(x) { return parseInt(x); });
var dp = [...Array(maxn)].map(e => Array(2*maxs));
for(var i = 0; i < maxn; ++i)
{
    for(var s = 0; s < 2 * maxs; ++s)
    {
        dp[i][s] = 0;
    }
}
for(var i = 1; i < n+1; ++i)
{
    for(var s = -maxs; s <= maxs; ++s)
    {
        dp[i][s+maxs] = (a[i]*a[i] == s*s)?1:0;
        if(s-a[i]>=-maxs)
                dp[i][s+maxs] += dp[i-1][s+maxs-a[i]];
        if(s+a[i]<=maxs)
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i]];
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    res += dp[i][maxs];
    res %= mod;
}
print(res);

const maxn = 1e3 + 5;
const maxs = 1e4 + 5;
const mod = 1e9 + 7;
var n  = parseInt(readline());
var a = [0] + readline().split(" ").map(function(x) { return parseInt(x); });
var dp = new Array(maxn).fill(0).map(() => new Array(2* maxs + 5).fill(0));
for(var i = 0; i < maxn; ++i)
{
    for(var s = 0; s < 2 * maxs; ++s)
    {
        dp[i][s] = 0;
    }
}
for(var i = 1; i < n+1; ++i)
{
    for(var s = -maxs; s <= maxs; ++s)
    {
        dp[i][s+maxs] = (a[i]*a[i] == s*s)?1:0;
        if(s-a[i]>=-maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs-a[i]];
        }
        if(s+a[i]<=maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i]];
        }
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    //print(res);
    res += dp[i][maxs];
    res %= mod;
}
print(res);

const maxn = 1e3 + 5;
const maxs = 1e4 + 5;
const mod = 1e9 + 7;
var n  = parseInt(readline());
var a = [0] + readline().split(" ").map(function(x) { return parseInt(x); });
var dp = new Array(maxn).fill(0).map(() => new Array(maxs).fill(0));
print(dp[0][0])
for(var i = 0; i < maxn; ++i)
{
    for(var s = 0; s < 2 * maxs; ++s)
    {
        dp[i][s] = 0;
    }
}
for(var i = 1; i < n+1; ++i)
{
    for(var s = -maxs; s <= maxs; ++s)
    {
        dp[i][s+maxs] = (a[i]*a[i] == s*s)?1:0;
        if(s-a[i]>=-maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs-a[i]];
        }
        if(s+a[i]<=maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i]];
        }
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    res += dp[i][maxs];
    res %= mod;
}
print(res);

const maxn = 1e3 + 5;
const maxs = 1e4 + 5;
const mod = 1e9 + 7;
var n  = parseInt(readline());
var a = [0] + readline().split(" ").map(function(x) { return parseInt(x); });
var dp = new Array(maxn).fill(0).map(() => new Array(maxs).fill(0));
print(a[0])
print(a[1])
for(var i = 0; i < maxn; ++i)
{
    for(var s = 0; s < 2 * maxs; ++s)
    {
        dp[i][s] = 0;
    }
}
for(var i = 1; i < n+1; ++i)
{
    for(var s = -maxs; s <= maxs; ++s)
    {
        dp[i][s+maxs] = (a[i]*a[i] == s*s)?1:0;
        if(s-a[i]>=-maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs-a[i]];
        }
        if(s+a[i]<=maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i]];
        }
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    print(res);
    res += dp[i][maxs];
    res %= mod;
}
print(res);

const maxn = 1e3 + 5;
const maxs = 1e4 + 5;
const mod = 1e9 + 7;
var n  = parseInt(readline());
var a = [0] + readline().split(" ").map(function(x) { return parseInt(x); });
var dp = [...Array(maxn)].map(e => Array(2*maxs));
for(var i = 1; i < n+1; ++i)
{
    for(var s = -maxs; s <= maxs; ++s)
    {
        dp[i][s+maxs] = (a[i]*a[i] == s*s);
        if(s-a[i]>=-maxs)
                dp[i][s+maxs] += dp[i-1][s+maxs-a[i]];
        if(s+a[i]<=maxs)
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i]];
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    res += dp[i][maxs];
    res %= mod;
}
print(res);

const maxn = 1e3 + 5;
const maxs = 1e4 + 5;
const mod = 1e9 + 7;
var n  = parseInt(readline());
var a = [0] + readline().split(" ").map(function(x) { return parseInt(x); });
var dp = new Array(maxn).fill(0).map(() => new Array(maxs).fill(0));
for(var i = 0; i < maxn; ++i)
{
    for(var s = 0; s < 2 * maxs; ++s)
    {
        dp[i][s] = 0;
    }
}
for(var i = 1; i < n+1; ++i)
{
    for(var s = -maxs; s <= maxs; ++s)
    {
        dp[i][s+maxs] = (a[i]*a[i] == s*s)?1:0;
        if(s-a[i]>=-maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs-a[i]];
        }
        if(s+a[i]<=maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i]];
        }
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    res += dp[i][maxs];
    res %= mod;
}
print(res);

const maxn = 1e3 + 5;
const maxs = 1e4 + 5;
const mod = 1e9 + 7;
var n  = parseInt(readline());
var a = [0] + readline().split(" ").map(function(x) { return parseInt(x); });
var dp = new Array(maxn).fill(0).map(() => new Array(2* maxs).fill(0));
for(var i = 0; i < maxn; ++i)
{
    for(var s = 0; s < 2 * maxs; ++s)
    {
        dp[i][s] = 0;
    }
}
for(var i = 1; i < n+1; ++i)
{
    for(var s = -maxs; s <= maxs; ++s)
    {
        dp[i][s+maxs] = (a[i]*a[i] == s*s)?1:0;
        if(s-a[i]>=-maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs-a[i]];
        }
        if(s+a[i]<=maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i]];
        }
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    //print(res);
    res += dp[i][maxs];
    res %= mod;
}
print(res);

const maxn = 1e3 + 5;
const maxs = 1e4 + 5;
const mod = 1e9 + 7;
var n  = parseInt(readline());
var a = [0] + readline().split(" ").map(function(x) { return parseInt(x); });
var dp = new Array(maxn).fill(0).map(() => new Array(maxs).fill(0));
print(n)
for(var i = 0; i < maxn; ++i)
{
    for(var s = 0; s < 2 * maxs; ++s)
    {
        dp[i][s] = 0;
    }
}
for(var i = 1; i < n+1; ++i)
{
    for(var s = -maxs; s <= maxs; ++s)
    {
        dp[i][s+maxs] = (a[i]*a[i] == s*s)?1:0;
        if(s-a[i]>=-maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs-a[i]];
        }
        if(s+a[i]<=maxs)
        {
            dp[i][s+maxs] += dp[i-1][s+maxs+a[i]];
        }
        dp[i][s+maxs]%=mod;
    }
}
var res = 0;
for(var i = 1; i < n + 1; ++i)
{
    res += dp[i][maxs];
    res %= mod;
}
print(res);


Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.

The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.  It is guaranteed that the given set of edges specifies a tree.

A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.

NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test:  The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test:  The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Queue = require('../queue');
var Stack = require('../stack');

var Graph = function () {
    function Graph() {
        var _this = this;

        var nodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var directed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        _classCallCheck(this, Graph);

        this.directed = directed;
        this.nodes = nodes;
        this.edges = {};
        nodes.forEach(function (node) {
            _this.edges[node] = [];
        });
    }

    _createClass(Graph, [{
        key: 'addNode',
        value: function addNode(node) {
            // is it required ?
            if (this.edges[node]) {
                throw new Error('Graph.prototype.addNode: node is already exists');
                return;
            }

            this.nodes.push(node);
            this.edges[node] = [];
        }
    }, {
        key: 'addEdge',
        value: function addEdge(node1, node2) {
            var weight = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;

            this.edges[node1].push({ node: node2, weight: weight });

            if (!this.directed) {
                this.edges[node2].push({ node: node1, weight: weight });
            }
        }
    }]);

    return Graph;
}();

module.exports = Graph;

},{"../queue":3,"../stack":4}],2:[function(require,module,exports){
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = function () {
    function Node(value) {
        _classCallCheck(this, Node);

        this.value = value;
        this.nextNode = null;
        this.prevNode = null;
    }

    _createClass(Node, [{
        key: "getValue",
        value: function getValue() {
            return this.value;
        }
    }, {
        key: "setValue",
        value: function setValue(value) {
            this.value = value;
        }
    }, {
        key: "setNext",
        value: function setNext(nextNodeLink) {
            this.nextNode = nextNodeLink;
        }
    }, {
        key: "setPrev",
        value: function setPrev(prevNodeLink) {
            this.prevNode = prevNodeLink;
        }
    }, {
        key: "getNext",
        value: function getNext() {
            return this.nextNode;
        }
    }, {
        key: "getPrev",
        value: function getPrev() {
            return this.prevNode;
        }
    }]);

    return Node;
}();

module.exports = Node;

},{}],3:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Queue = function () {
    function Queue() {
        _classCallCheck(this, Queue);

        this.firstItemLink = null;
        this.lastItemLink = null;
    }

    _createClass(Queue, [{
        key: 'enqueue',
        value: function enqueue(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.lastItemLink = node;
                this.firstItemLink = node;
            } else {
                this.lastItemLink.setNext(node);
                this.lastItemLink = node;
            }

            return node;
        }
    }, {
        key: 'dequeue',
        value: function dequeue() {
            if (this.isEmpty()) {
                return undefined;
            }

            if (this.lastItemLink === this.firstItemLink) {
                this.lastItemLink = null;
            }

            var firstItem = this.firstItemLink;

            this.firstItemLink = this.firstItemLink.getNext();

            return firstItem.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.firstItemLink;
        }
    }]);

    return Queue;
}();

module.exports = Queue;

},{"../node":2}],4:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Stack = function () {
    function Stack() {
        _classCallCheck(this, Stack);

        this.topItemLink = null;
    }

    _createClass(Stack, [{
        key: 'push',
        value: function push(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.topItemLink = node;
            } else {
                node.setPrev(this.topItemLink);
                this.topItemLink = node;
            }

            return node;
        }
    }, {
        key: 'pop',
        value: function pop() {
            if (this.isEmpty()) {
                return undefined;
            }

            var topItemLink = this.topItemLink;

            this.topItemLink = this.topItemLink.getPrev();

            return topItemLink.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.topItemLink;
        }
    }]);

    return Stack;
}();

module.exports = Stack;

},{"../node":2}],5:[function(require,module,exports){
'use strict';

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

var Graph = require('../libs/graph');
var Queue = require('../libs/queue');

var _readline$split$map = readline().split(' ').map(function (v) {
    return parseInt(v);
}),
    _readline$split$map2 = _slicedToArray(_readline$split$map, 2),
    n = _readline$split$map2[0],
    maxCats = _readline$split$map2[1];

var hasCat = readline().split(' ').map(function (v) {
    return parseInt(v);
});

// BFS - с проставлением количества котов для каждой ноды
// Ноды, которые не имеют direct edge сохраняем в массив листья

var G = new Graph();

for (var i = 1; i <= n; i++) {
    G.addNode(i);
}

for (var _i = 1; _i < n; _i++) {
    var _readline$split$map3 = readline().split(' ').map(function (v) {
        return parseInt(v);
    }),
        _readline$split$map4 = _slicedToArray(_readline$split$map3, 2),
        n1 = _readline$split$map4[0],
        n2 = _readline$split$map4[1];

    G.addEdge(n1, n2);
}

var catsAmount = {
    1: hasCat[0]
};

var leaves = [];

var q = new Queue();
q.enqueue(1);

var visited = new Set();

var _loop = function _loop() {
    var node = q.dequeue();
    visited.add(node);

    if (G.edges[node].length === 1 && node !== 1) {
        leaves.push(node);
    } else {
        G.edges[node].forEach(function (_ref) {
            var child = _ref.node;

            if (visited.has(child)) {
                return;
            }

            var catsAmountInParent = catsAmount[node];
            var catsAmountInChild = hasCat[child - 1];

            if (catsAmountInChild) {
                catsAmount[child] = catsAmountInParent + 1;
            } else {
                catsAmount[child] = 0;
            }

            if (catsAmount[child] <= maxCats) q.enqueue(child);
        });
    }
};

while (!q.isEmpty()) {
    _loop();
}

write(leaves.length);

},{"../libs/graph":1,"../libs/queue":3}]},{},[5]);

const res = [];

function buildTree(n, edges, cats) {
  edges = edges.map(edge => {
    return edge.split(' ').map(el => {
      return parseInt(el, 10);
    });
  });
  var edges2 = edges.map(edge => {
    return [edge[1], edge[0]];
  });
  edges = edges.concat(edges2);
  edges.sort((a, b) => {
    return a[0] - b[0];
  });
  var tree = [];
  var j = 0;
  for (var i = 1; i <= n; i++) {
    var node = {
      n: i,
      hasCat: parseInt(cats[i - 1], 10) === 1,
      children: [],
      visited: false,
      cats: 0,
      fatherCats: 0
    };
    while (edges[j] && edges[j][0] === i) {
      node.children.push(edges[j][1]);
      j++;
    }
    tree.push(node);
  }
  return tree;
}

const stack = [];

function resolve(tree, m) {
  var node;
  while (stack.length > 0) {
    node = stack.pop();
    if (!node.visited) {
      node.visited = true;
      if (!node.hasCat) {
        node.cats = 0;
      } else {
        node.cats = node.fatherCats + 1;
      }
      if (node.cats <= m) {
        var count = 0;
        for (var i = 0; i < node.children.length; i++) {
          if (!tree[node.children[i] - 1].visited) {
            count++;
            tree[node.children[i] - 1].fatherCats = node.cats;
            stack.push(tree[node.children[i] - 1]);
          }
        }
        if (count === 0) {
          res.push(node.n);
        }
      }
    }
  }
}

/*
const tree = buildTree(
  15,
  [
    '1 2',
    '1 3',
    '2 4',
    '2 5',
    '3 6',
    '3 7',
    '4 8',
    '4 9',
    '5 10',
    '5 11',
    '6 12',
    '6 13',
    '7 14',
    '7 15'
  ],
  ['1', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
);
console.log(tree);
stack.push(tree[0]);
resolve(tree, 2);
console.log(res);
*/

const i = readline().split(' ');
const n = parseInt(i[0], 10);
const m = parseInt(i[1], 10);
const cats = readline().split(' ');
const edges = [];
var edge = readline();
while (edge) {
  edges.push(edge);
  edge = readline();
}
const tree = buildTree(n, edges, cats);
stack.push(tree[0]);
resolve(tree, m);
print(res.length);

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Queue = require('../queue');
var Stack = require('../stack');

var Graph = function () {
    function Graph() {
        var _this = this;

        var nodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var directed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        _classCallCheck(this, Graph);

        this.directed = directed;
        this.nodes = nodes;
        this.edges = {};
        nodes.forEach(function (node) {
            _this.edges[node] = [];
        });
    }

    _createClass(Graph, [{
        key: 'addNode',
        value: function addNode(node) {
            // is it required ?
            if (this.edges[node]) {
                throw new Error('Graph.prototype.addNode: node is already exists');
                return;
            }

            this.nodes.push(node);
            this.edges[node] = [];
        }
    }, {
        key: 'addEdge',
        value: function addEdge(node1, node2) {
            var weight = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;

            this.edges[node1].push({ node: node2, weight: weight });

            if (!this.directed) {
                this.edges[node2].push({ node: node1, weight: weight });
            }
        }
    }]);

    return Graph;
}();

module.exports = Graph;

},{"../queue":3,"../stack":4}],2:[function(require,module,exports){
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = function () {
    function Node(value) {
        _classCallCheck(this, Node);

        this.value = value;
        this.nextNode = null;
        this.prevNode = null;
    }

    _createClass(Node, [{
        key: "getValue",
        value: function getValue() {
            return this.value;
        }
    }, {
        key: "setValue",
        value: function setValue(value) {
            this.value = value;
        }
    }, {
        key: "setNext",
        value: function setNext(nextNodeLink) {
            this.nextNode = nextNodeLink;
        }
    }, {
        key: "setPrev",
        value: function setPrev(prevNodeLink) {
            this.prevNode = prevNodeLink;
        }
    }, {
        key: "getNext",
        value: function getNext() {
            return this.nextNode;
        }
    }, {
        key: "getPrev",
        value: function getPrev() {
            return this.prevNode;
        }
    }]);

    return Node;
}();

module.exports = Node;

},{}],3:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Queue = function () {
    function Queue() {
        _classCallCheck(this, Queue);

        this.firstItemLink = null;
        this.lastItemLink = null;
    }

    _createClass(Queue, [{
        key: 'enqueue',
        value: function enqueue(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.lastItemLink = node;
                this.firstItemLink = node;
            } else {
                this.lastItemLink.setNext(node);
                this.lastItemLink = node;
            }

            return node;
        }
    }, {
        key: 'dequeue',
        value: function dequeue() {
            if (this.isEmpty()) {
                return undefined;
            }

            if (this.lastItemLink === this.firstItemLink) {
                this.lastItemLink = null;
            }

            var firstItem = this.firstItemLink;

            this.firstItemLink = this.firstItemLink.getNext();

            return firstItem.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.firstItemLink;
        }
    }]);

    return Queue;
}();

module.exports = Queue;

},{"../node":2}],4:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Stack = function () {
    function Stack() {
        _classCallCheck(this, Stack);

        this.topItemLink = null;
    }

    _createClass(Stack, [{
        key: 'push',
        value: function push(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.topItemLink = node;
            } else {
                node.setPrev(this.topItemLink);
                this.topItemLink = node;
            }

            return node;
        }
    }, {
        key: 'pop',
        value: function pop() {
            if (this.isEmpty()) {
                return undefined;
            }

            var topItemLink = this.topItemLink;

            this.topItemLink = this.topItemLink.getPrev();

            return topItemLink.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.topItemLink;
        }
    }]);

    return Stack;
}();

module.exports = Stack;

},{"../node":2}],5:[function(require,module,exports){
'use strict';

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

var Graph = require('../libs/graph');
var Queue = require('../libs/queue');

var _readline$split$map = readline().split(' ').map(function (v) {
    return parseInt(v);
}),
    _readline$split$map2 = _slicedToArray(_readline$split$map, 2),
    n = _readline$split$map2[0],
    maxCats = _readline$split$map2[1];

var hasCat = readline().split(' ').map(function (v) {
    return parseInt(v);
});

// BFS - с проставлением количества котов для каждой ноды
// Ноды, которые не имеют direct edge сохраняем в массив листья

var G = new Graph([], true);

for (var i = 1; i <= n; i++) {
    G.addNode(i);
}

for (var _i = 1; _i < n; _i++) {
    var _readline$split$map3 = readline().split(' ').map(function (v) {
        return parseInt(v);
    }),
        _readline$split$map4 = _slicedToArray(_readline$split$map3, 2),
        n1 = _readline$split$map4[0],
        n2 = _readline$split$map4[1];

    G.addEdge(n1, n2);
}

var catsAmount = {
    1: hasCat[0]
};

var leaves = [];

var q = new Queue();
q.enqueue(1);

var _loop = function _loop() {
    var node = q.dequeue();

    if (G.edges[node].length === 0) {
        leaves.push(node);
    } else {
        G.edges[node].forEach(function (_ref) {
            var child = _ref.node;

            var catsAmountInParent = catsAmount[node];
            var catsAmountInChild = hasCat[child - 1];

            if (catsAmountInChild) {
                catsAmount[child] = catsAmountInParent + 1;
            } else {
                catsAmount[child] = 0;
            }

            if (catsAmount[child] <= maxCats) q.enqueue(child);
        });
    }
};

while (!q.isEmpty()) {
    _loop();
}

write(leaves.length);

},{"../libs/graph":1,"../libs/queue":3}]},{},[5]);

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Queue = require('../queue');
var Stack = require('../stack');

var Graph = function () {
    function Graph() {
        var _this = this;

        var nodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var directed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        _classCallCheck(this, Graph);

        this.directed = directed;
        this.nodes = nodes;
        this.edges = {};
        nodes.forEach(function (node) {
            _this.edges[node] = [];
        });
    }

    _createClass(Graph, [{
        key: 'addNode',
        value: function addNode(node) {
            // is it required ?
            if (this.edges[node]) {
                throw new Error('Graph.prototype.addNode: node is already exists');
                return;
            }

            this.nodes.push(node);
            this.edges[node] = [];
        }
    }, {
        key: 'addEdge',
        value: function addEdge(node1, node2) {
            var weight = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;

            this.edges[node1].push({ node: node2, weight: weight });

            if (!this.directed) {
                this.edges[node2].push({ node: node1, weight: weight });
            }
        }
    }]);

    return Graph;
}();

module.exports = Graph;

},{"../queue":3,"../stack":4}],2:[function(require,module,exports){
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = function () {
    function Node(value) {
        _classCallCheck(this, Node);

        this.value = value;
        this.nextNode = null;
        this.prevNode = null;
    }

    _createClass(Node, [{
        key: "getValue",
        value: function getValue() {
            return this.value;
        }
    }, {
        key: "setValue",
        value: function setValue(value) {
            this.value = value;
        }
    }, {
        key: "setNext",
        value: function setNext(nextNodeLink) {
            this.nextNode = nextNodeLink;
        }
    }, {
        key: "setPrev",
        value: function setPrev(prevNodeLink) {
            this.prevNode = prevNodeLink;
        }
    }, {
        key: "getNext",
        value: function getNext() {
            return this.nextNode;
        }
    }, {
        key: "getPrev",
        value: function getPrev() {
            return this.prevNode;
        }
    }]);

    return Node;
}();

module.exports = Node;

},{}],3:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Queue = function () {
    function Queue() {
        _classCallCheck(this, Queue);

        this.firstItemLink = null;
        this.lastItemLink = null;
    }

    _createClass(Queue, [{
        key: 'enqueue',
        value: function enqueue(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.lastItemLink = node;
                this.firstItemLink = node;
            } else {
                this.lastItemLink.setNext(node);
                this.lastItemLink = node;
            }

            return node;
        }
    }, {
        key: 'dequeue',
        value: function dequeue() {
            if (this.isEmpty()) {
                return undefined;
            }

            if (this.lastItemLink === this.firstItemLink) {
                this.lastItemLink = null;
            }

            var firstItem = this.firstItemLink;

            this.firstItemLink = this.firstItemLink.getNext();

            return firstItem.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.firstItemLink;
        }
    }]);

    return Queue;
}();

module.exports = Queue;

},{"../node":2}],4:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Stack = function () {
    function Stack() {
        _classCallCheck(this, Stack);

        this.topItemLink = null;
    }

    _createClass(Stack, [{
        key: 'push',
        value: function push(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.topItemLink = node;
            } else {
                node.setPrev(this.topItemLink);
                this.topItemLink = node;
            }

            return node;
        }
    }, {
        key: 'pop',
        value: function pop() {
            if (this.isEmpty()) {
                return undefined;
            }

            var topItemLink = this.topItemLink;

            this.topItemLink = this.topItemLink.getPrev();

            return topItemLink.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.topItemLink;
        }
    }]);

    return Stack;
}();

module.exports = Stack;

},{"../node":2}],5:[function(require,module,exports){
'use strict';

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

var Graph = require('../libs/graph');
var Queue = require('../libs/queue');

var _readline$split$map = readline().split(' ').map(function (v) {
    return parseInt(v);
}),
    _readline$split$map2 = _slicedToArray(_readline$split$map, 2),
    n = _readline$split$map2[0],
    maxCats = _readline$split$map2[1];

var hasCat = readline().split(' ').map(function (v) {
    return parseInt(v);
});

// BFS - с проставлением количества котов для каждой ноды
// Ноды, которые не имеют direct edge сохраняем в массив листья

var G = new Graph([], true);

for (var i = 1; i <= n; i++) {
    G.addNode(i);
}

for (var _i = 1; _i < n; _i++) {
    var _readline$split$map$s = readline().split(' ').map(function (v) {
        return parseInt(v);
    }).sort(function (a, b) {
        return a - b;
    }),
        _readline$split$map$s2 = _slicedToArray(_readline$split$map$s, 2),
        n1 = _readline$split$map$s2[0],
        n2 = _readline$split$map$s2[1];

    G.addEdge(n1, n2);
}

var catsAmount = {
    1: hasCat[0]
};

var leaves = [];

var q = new Queue();
q.enqueue(1);

var _loop = function _loop() {
    var node = q.dequeue();

    if (G.edges[node].length === 0) {
        leaves.push(node);
    } else {
        G.edges[node].forEach(function (_ref) {
            var child = _ref.node;

            var catsAmountInParent = catsAmount[node];
            var catsAmountInChild = hasCat[child - 1];

            if (catsAmountInChild) {
                catsAmount[child] = catsAmountInParent + 1;
            } else {
                catsAmount[child] = 0;
            }

            if (catsAmount[child] <= maxCats) q.enqueue(child);
        });
    }
};

while (!q.isEmpty()) {
    _loop();
}

write(leaves.length);

},{"../libs/graph":1,"../libs/queue":3}]},{},[5]);

const res = [];

function buildTree(n, edges, cats) {
  edges = edges.map(edge => {
    return edge
      .split(' ')
      .map(el => {
        return parseInt(el, 10);
      })
      .sort((a, b) => {
        return a - b;
      });
  });
  edges.sort((a, b) => {
    return a[0] - b[0];
  });
  var tree = [];
  var j = 0;
  for (var i = 1; i <= n; i++) {
    var node = {
      n: i,
      hasCat: parseInt(cats[i - 1], 10) === 1,
      children: []
    };
    while (edges[j] && edges[j][0] === i) {
      node.children.push(edges[j][1]);
      j++;
    }
    tree.push(node);
  }
  return tree;
}

function resolve(node, tree, cats, m) {
  if (!node.hasCat) {
    cats = 0;
  } else {
    cats++;
  }
  if (cats <= m) {
    if (node.children.length === 0) {
      res.push(node.n);
    }
    for (var i = 0; i < node.children.length; i++) {
      resolve(tree[node.children[i] - 1], tree, cats, m);
    }
  }
}

/*
const tree = buildTree(
  15,
  [
    '1 2',
    '1 3',
    '2 4',
    '2 5',
    '3 6',
    '3 7',
    '4 8',
    '4 9',
    '5 10',
    '5 11',
    '6 12',
    '6 13',
    '7 14',
    '7 15'
  ],
  ['1', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
);
console.log(tree);
resolve(tree[0], tree, 0, 2);
console.log(res);
*/

const i = readline().split(' ');
const n = parseInt(i[0], 10);
const m = parseInt(i[1], 10);
const cats = readline().split(' ');
const edges = [];
var edge = readline();
while (edge) {
  edges.push(edge);
  edge = readline();
}
const tree = buildTree(n, edges, cats);
resolve(tree[0], tree, 0, m);
print(res.length);

const res = [];

function buildTree(n, edges, cats) {
  edges.sort();
  var tree = [];
  var j = 0;
  for (var i = 1; i <= n; i++) {
    var node = {
      n: i,
      hasCat: parseInt(cats[i - 1], 10) === 1,
      children: []
    };
    while (edges[j] && edges[j][0] === i) {
      node.children.push(edges[j][1]);
      j++;
    }
    tree.push(node);
  }
  return tree;
}

function resolve(node, tree, cats, m) {
  if (!node.hasCat) {
    cats = 0;
  } else {
    cats++;
  }
  if (cats <= m) {
    if (node.children.length === 0) {
      res.push(node.n);
    }
    for (var i = 0; i < node.children.length; i++) {
      resolve(tree[node.children[i] - 1], tree, cats, m);
    }
  }
}

/*
const tree = buildTree(4, ['1 2', '1 3', '1 4'], ['1', '1', '0', '0']);
resolve(tree[0], tree, 0, 1);
console.log(res);
*/

const i = readline().split(' ');
const n = parseInt(i[0], 10);
const m = parseInt(i[1], 10);
const cats = readline().split(' ');
const edges = [];
var edge = readline();
while (edge) {
  edge = edge
    .split(' ')
    .map(el => {
      return parseInt(el, 10);
    })
    .sort();
  edges.push(edge);
  edge = readline();
}
const tree = buildTree(n, edges, cats);
resolve(tree[0], tree, 0, m);
print(res.length);

const res = [];

function buildTree(n, edges, cats) {
  edges.sort();
  var tree = [];
  var j = 0;
  for (var i = 1; i <= n; i++) {
    var node = {
      n: i,
      hasCat: parseInt(cats[i - 1], 10) === 1,
      children: []
    };
    while (edges[j] && parseInt(edges[j].split(' ')[0], 10) === i) {
      node.children.push(parseInt(edges[j].split(' ')[1], 10));
      j++;
    }
    tree.push(node);
  }
  return tree;
}

function resolve(node, tree, cats, m) {
  if (!node.hasCat) {
    cats = 0;
  } else {
    cats++;
  }
  if (cats <= m) {
    if (node.children.length === 0) {
      res.push(node.n);
    }
    for (var i = 0; i < node.children.length; i++) {
      resolve(tree[node.children[i] - 1], tree, cats, m);
    }
  }
}

/*
const tree = buildTree(4, ['1 2', '1 3', '1 4'], ['1', '1', '0', '0']);
resolve(tree[0], tree, 0, 1);
console.log(res);
*/

const i = readline().split(' ');
const n = parseInt(i[0], 10);
const m = parseInt(i[1], 10);
const cats = readline().split(' ');
const edges = [];
for (var j = 0; j < n; j++) {
  edges.push(readline());
}
const tree = buildTree(n, edges, cats);
resolve(tree[0], tree, 0, m);
print(res.length);

const res = [];

function buildTree(n, edges, cats) {
  edges.sort();
  edges = edges.map(edge => {
    return edge
      .split(' ')
      .map(el => {
        return parseInt(el, 10);
      })
      .sort();
  });
  var tree = [];
  var j = 0;
  for (var i = 1; i <= n; i++) {
    var node = {
      n: i,
      hasCat: parseInt(cats[i - 1], 10) === 1,
      children: []
    };
    while (edges[j] && edges[j][0] === i) {
      node.children.push(edges[j][1]);
      j++;
    }
    tree.push(node);
  }
  return tree;
}

function resolve(node, tree, cats, m) {
  if (!node.hasCat) {
    cats = 0;
  } else {
    cats++;
  }
  if (cats <= m) {
    if (node.children.length === 0) {
      res.push(node.n);
    }
    for (var i = 0; i < node.children.length; i++) {
      resolve(tree[node.children[i] - 1], tree, cats, m);
    }
  }
}

/*
const tree = buildTree(4, ['1 2', '1 3', '1 4'], ['1', '1', '0', '0']);
resolve(tree[0], tree, 0, 1);
console.log(res);
*/

const i = readline().split(' ');
const n = parseInt(i[0], 10);
const m = parseInt(i[1], 10);
const cats = readline().split(' ');
const edges = [];
var edge = readline();
while (edge) {
  edges.push(edge);
  edge = readline();
}
const tree = buildTree(n, edges, cats);
resolve(tree[0], tree, 0, m);
print(res.length);


Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:  Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).  The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries.

The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).

Print m integers — the responses to Eugene's queries in the order they occur in the input.

print(function(n, m) {

	var x = 0,
		y = 0,
		ans = new Int8Array(m);
	rn().forEach(function(v) {
		if (v === 1) x++;
		else y++;
	});

	x = Math.min(x, y) * 2;

	for (var i = 0; i < m; i++)
		ans[i] = rn().reduce(function(l, r) {
			if (r - l + 1 > x || (r - l) % 2 === 0) return 0;
			return 1;
		});

	return [].join.call(ans, '\n');

} .apply(0, rn()));

function rn() {
	return readline().split(' ').map(Number);
}

print(function(n, m) {

	var x = 0,
		y = 0,
		ans = new Int8Array(m);
	readline().split(' ').map(Number).forEach(function(v) {
		if (v === 1) x++;
		else y++;
	});

	x = Math.min(x, y) * 2;

	for (var i = 0; i < m; i++)
		ans[i] = readline().split(' ').map(Number).reduce(function(l, r) {
			if (r - l + 1 > x || (r - l) % 2 === 0) return 0;
			return 1;
		});

	return [].join.call(ans, '\n');

} .apply(0, readline().split(' ').map(Number)));

print(function(n, m) {

	var x = 0,
		y = 0,
		ans = new Int8Array(m),
		a = rn();

	for (var i = 0; i < n; i++)
		if (a[i] === 1) x++;
		else y++;

	x = Math.min(x, y) * 2;

	for (var i = 0; i < m; i++) {
		var l = rn();
		ans[i] = l[1] - l[0] + 1 > x || (l[1] - l[0]) % 2 === 0 ? 0 : 1;
	}

	return [].join.call(ans, '\n');

} .apply(0, rn()));

function rn() {
	return readline().split(' ').map(Number);
}

print(function(n, m) {

	var x = 0,
		y = 0,
		ans = [];
	rn().forEach(function(v) {
		if (v === 1) x++;
		else y++;
	});

	x = Math.min(x, y) * 2;

	for (var i = 0; i < m; i++)
		ans.push(rn().reduce(function(l, r) {
			if (r - l + 1 > x || (r - l) % 2 === 0) return 0;
			return 1;
		}));

	return ans.join('\n');

} .apply(0, rn()));

function rn() {
	return readline().split(' ').map(Number);
}

;(function () {
	print(function (n, m) {
		var q = {}, t = [];

		readline().split(' ').forEach(function (e) {
			q[e] = q[e] ? q[e] + 1 : 1;
		});

		while (m--) {
			var l = readline().split(' ').map(Number); l = l[1] - l[0] + 1;
			t.push(((l%2) === 0 && q['1'] >= l/2 && q['-1'] >= l/2) ? 1 : 0);
		}

		return t.join('\n');
	}.apply(null, readline().split(' ').map(Number)));
}.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 data = tokenizeIntegers(readline()),
		n = data[0], m = data[1],
		numbers = tokenizeIntegers(readline()),
		positive = 0, negative = 0;
	for (var i = 0; i < n; ++i) {
		if (numbers[i] == -1) {
			negative += 1;
		} else {
			positive += 1;
		}
	}
	var result = [];
	for (var i = 0; i < m; ++i) {
		data = tokenizeIntegers(readline());
		var span = data[1] - data[0] + 1;
		if (span % 2 == 0 && span <= 2*negative && span <= 2*positive) {
			result.push(1);
		} else {
			result.push(0);
		}
	}
	print(result.join('\n'));
}

main();

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

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

  if (c === 1) {
    c++;
    arr = d.split(' ').map(Number);
    return;
  }

  m.push(d.split(' ').map(Number));

  c++;
});

rl.on('close', () => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 1) {
      ones++;
    }
    else {
      minusOnes++;
    }
  }

  let ans = '';
  for (let j = 0; j < m.length; j++) {
    const [a, b] = m[j];
    const amount = b - a + 1;
    const half = amount / 2;

    if (amount % 2 === 1) {
      ans += '0\n';
    }
    else if (half <= ones && half <= minusOnes) {
      ans += '1\n';
    }
    else {
      ans += '0\n';
    }
  }

  console.log(ans);
});

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

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

  if (c === 1) {
    c++;
    arr = d.split(' ').map(Number);

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

  const [a, b] = d.split(' ').map(Number);
  const amount = b - a + 1;

  if (amount % 2 === 1) {
    console.log(0);
  }
  else {
    console.log(1);
    // if (amount / 2 <= ones && amount / 2 <= minusOnes) {
    //   console.log(1);
    // }
    // else {
    //   console.log(0);
    // }
  }

  c++;
});

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

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

  if (c === 1) {
    c++;
    arr = d.split(' ');

    for (let i = 1; i <= arr.length; i += 2) {
      if (arr[i - 1] === '1') {
        ones++;
      }
      else {
        minusOnes++;
      }
      if (arr[i] === '1') {
        ones++;
      }
      else {
        minusOnes++;
      }
    }
    return;
  }

  const [a, b] = d.split(' ').map(Number);
  const amount = b - a + 1;

  if (amount % 2 === 1) {
    console.log(0);
  }
  else {
    if (amount / 2 <= ones && amount / 2 <= minusOnes) {
      console.log(1);
    }
    else {
      console.log(0);
    }
  }

  c++;
});

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    [n, m] = d.split(' ').map(Number);
    return;
  }

  if (c === 1) {
    c++;
    str = ' ' + d;
    ones = d.split('-1').length;
    return;
  }

  const [a, b] = d.split(' ').map(Number);
  const amount = b - a + 1;

  if (amount % 2 === 1) {
    console.log(0);
  }
  else {
    if (amount / 2 <= ones && amount / 2 <= n - ones) {
      console.log(1);
    }
    else {
      console.log(0);
    }
  }

  c++;
});


ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.

The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... < tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.

Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.

NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 > 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.

var c = readline().split(' ').map((val) => parseInt(val))[1];
var t = readline().split(' ').map((val) => parseInt(val));
var last_t = 0, count = 0;
for (var el of t) {
    count = el - last_t > c ? 1 : count + 1;
    last_t = el
}
print(count);

var c = readline().split(' ').map(Number)[1];
var last_t = 0, count = 0;
readline().split(' ').map(Number).forEach((el) => {
    count = el - last_t > c ? 1 : count + 1;
    last_t = el
});
print(count);

var c = readline().split(' ').map(Number)[1];
var t = readline().split(' ').map(Number);
var last_t = 0, count = 0;
for (var el of t) {
    count = el - last_t > c ? 1 : count + 1;
    last_t = el
}
print(count);

var c = readline().split(' ').map((val) => parseInt(val))[1];
var t = readline().split(' ').map((val) => parseInt(val));

var last_t = 0, count = 0;
for (var el of t) {
    if (el - last_t > c) {
        count = 1
    } else {
        count += 1
    }
    last_t = el
}
print(count);

var b = readline().split(" ");
	var n = b[0];
	var c = b[1];
    var a = readline().split(" ");
	var len = a.length;
	var ans = 1;
	for(var j = 0; j < len-1; j++)
	{
		if((a[j+1] - a[j])<=c ){
			++ans;
		}
		else {
			ans = 1;
		}
	}
	print(ans);

var s = readline().split(" ");
var str =  readline().split(" ");
var res = 0;
		for (var i=0; i<+s[0]; i++){
			res++;
			if (+str[i+1]-Number(str[i])>+s[1]){
				res = 0;
			}

		}
print(res);

var count = 0;
var c = readline().split(" ").map(Number)[1],
    last = 1;
readline().split(" ").map(Number).forEach(function(val){
    if (last) count = val - last > c ? 1 : count + 1;
    last = val
});

write(count);

var count = 0;
var c = readline().split(" ").map(Number)[1],
    last = 1;
readline().split(" ").map(Number).forEach(function(val){
    if (last) count = val - last <= c ? count + 1 : 1;
    last = val
});

write(count);

N=readline().split(' ').map(x=>+x)
T=readline().split(' ').map(x=>+x)
var R=1
for (var i=1;i<T.length;++i) {
 if (T[i]-T[i-1]>N[1])
  R=1
 else R++
}
print(R)

var l1 = readline().split(' ');
var t = readline().split(' ').map(function(a){return parseInt(a);});
var s = l1[0]===0 ? 0 : 1;
for(var i=l1[0]-2; i>=0; i--){
    if(t[i+1]-t[i]>l1[1]) break;
    s++;
}
print(s);

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var one = nextIntArray();
  var N = one[0];
  var C = one[1];
  var list = nextIntArray();
  var count = 1;
  for(var i = 1; i < N; i++){
    if(list[i] - list[i - 1] <= C){
      count++;
    }else{
      count = 1;
    }
  }
  myout(count);
}

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

rl.on('line', (d) => {
  if (count === 0) {
    [n, c] = d.split(' ').map(Number);
    count++;
    return;
  }

  const arr = d.split(' ').map(Number);
  let ans = 1;

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] - arr[i - 1] > c) {
      ans = 1;
    }
    else {
      ans++;
    }
  }

  console.log(ans);

  count++;
});

try {require('codef');} catch (e){global = this};
function readLineAsArray(separator){return readline().split(typeof separator == "undefined" ? ' ' : separator)}
function readLineAsIntegerArray(separator){return readLineAsArray(separator).map(function(v){return +v})}

var count = 0;
var t = readLineAsIntegerArray(),
    n = t[0],
    c = t[1];
last = 0;
readLineAsIntegerArray().forEach(function(val, index){
    if (last) count = val - last > c ? 1 : count + 1;
    last = val
});

write(count);

var line = readline();
var alp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function check(start){
    var map = {}, ch = "";
    for(var i = start; i < start + 26; i++) {
        ch = line[i];
        if (map[ch]) return false;
        if (ch == "?") continue;
        map[ch] = 1
    }
    return true
}

var index = -1;
if (line.length < 26) {
    write(-1);
} else {
    for(var i = 0; i <= line.length - 26; i++) {
        if (check(i)) {index = i; break}
    }
    if (index == -1) {
        write(-1)
    } else {
        var res = "";
        var repl = "";
        for(var i= 0; i < index; i++) res += line[i] == "?" ? "A" : line[i]
        for(var i = index; i < index + 26; i++) repl += line[i];
        alp = alp.replace(/[A-Z]/g, function (ch) {return repl.indexOf(ch) > -1 ? "" : ch}).split("")
        for(var i = index; i < index + 26; i++) res += line[i] == "?" ? alp.pop() : line[i]
        for(var i= index + 26; i < line.length; i++) res += line[i] == "?" ? "A" : line[i]
        write(res);
    }
}

try {require('codef');} catch (e){global = this};
function readLineAsArray(separator){return readline().split(typeof separator == "undefined" ? ' ' : separator)}
function readLineAsIntegerArray(separator){return readLineAsArray(separator).map(function(v){return +v})}

var count = 1;
var t = readLineAsIntegerArray(),
    n = t[0],
    c = t[1];
last = 1;
readLineAsIntegerArray().forEach(function(val, index){
    if (last) count = val - last > c ? 1 : count + 1;
    last = val
});

write(count);


You are given an array $$$a_1, a_2, \ldots, a_n$$$ consisting of $$$n$$$ positive integers and a positive integer $$$m$$$.You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.Let's call an array $$$m$$$-divisible if for each two adjacent numbers in the array (two numbers on the positions $$$i$$$ and $$$i+1$$$ are called adjacent for each $$$i$$$) their sum is divisible by $$$m$$$. An array of one element is $$$m$$$-divisible.Find the smallest number of $$$m$$$-divisible arrays that $$$a_1, a_2, \ldots, a_n$$$ is possible to divide into.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \le n \le 10^5, 1 \le m \le 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.

For each test case print the answer to the problem.

NoteIn the first test case we can divide the elements as follows:  $$$[4, 8]$$$. It is a $$$4$$$-divisible array because $$$4+8$$$ is divisible by $$$4$$$.  $$$[2, 6, 2]$$$. It is a $$$4$$$-divisible array because $$$2+6$$$ and $$$6+2$$$ are divisible by $$$4$$$.  $$$[9]$$$. It is a $$$4$$$-divisible array because it consists of one element.

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

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

function main () {
	let t = rn();
	while (t--) {
		let [n, m] = rna();
		let a = rna();

		let cnt = Array(m).fill(0);
		for (elm of a)
			cnt[elm % m]++;

		let ans = 0;
		for (let i = 0; i < m; i++) {
			if (cnt[i]) {
				if (2 * i % m == 0) {
					ans++;
					continue;
				}
				ans1 = Math.max(0, cnt[i] - Math.min(cnt[i], cnt[m-i]) - 1);
				ans2 = Math.max(0, cnt[m-i] - Math.min(cnt[i], cnt[m-i]) - 1);
				ans += 1 + ans1 + ans2;
				cnt[i] = cnt[m-i] = 0;
			}
		}
		console.log(ans);
	}
}

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

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

function main () {
	let t = rn();
	while (t--) {
		let [n, m] = rna();
		let a = rna();

		let cnt = Array(m + 1).fill(0);
		for (x of a)
			cnt[x % m]++;

		let ans = 0;
		for (let i = 0; i < m; i++) {
			if (cnt[i]){
				if (i == 0 || i == m - i) {
					ans++;
					continue;
				}
				ans1 = Math.max(0, cnt[i] - Math.min(cnt[i], cnt[m-i]) - 1);
				ans2 = Math.max(0, cnt[m-i] - Math.min(cnt[i], cnt[m-i]) - 1);
				ans += 1 + ans1 + ans2;
				cnt[i] = cnt[m-i] = 0;
			}
		}
		console.log(ans);
	}
}

///////////////////////////////// pre-define /////////////////////////////////////
const pr = console.log;
const mx = Math.max;
///////////////////////////////////////////////////////////////////////////////////

const solve = (n, m, a) => {
    let cnt = Array(m).fill(0);
    for (const e of a) cnt[e % m]++;
    let res = 0;
    for (let i = 0; i <= m >> 1; i++) {
        let j = (m - i) % m;
        if (!cnt[i] && !cnt[j]) continue;
        if (i != j) {
            res += mx(1, cnt[i] >= cnt[j] ? cnt[i] - cnt[j] : cnt[j] - cnt[i]);
        } else {
            res++;
        }
    }
    pr(res)
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i][1], input[i + 1]);
            i += 2;
        }
    });
};

main()

///////////////////////////////// pre-define /////////////////////////////////////
const pr = console.log;
const mx = Math.max;
///////////////////////////////////////////////////////////////////////////////////

const solve = (n, m, a) => {
    let cnt = Array(m).fill(0);
    for (const e of a) cnt[e % m]++;
    let res = 0;
    for (let i = 0; i <= m >> 1; i++) {
        let j = (m - i) % m;
        if (!cnt[i] && !cnt[j]) continue;
        if (i != j) {
            res += mx(1, Math.abs(cnt[i] - cnt[j]));
        } else {
            res++;
        }
    }
    pr(res)
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i][1], input[i + 1]);
            i += 2;
        }
    });
};

main()

///////////////////////////////// pre-define /////////////////////////////////////
const pr = console.log;
const mx = Math.max
///////////////////////////////////////////////////////////////////////////////////

const solve = (n, m, a) => {
    let cnt = Array(m).fill(0);
    for (const e of a) cnt[e % m]++;
    let res = 0;
    for (let i = 0; i <= m >> 1; i++) {
        let j = (m - i) % m;
        if (!cnt[i] && !cnt[j]) continue;
        if (i != j) {
            let x = cnt[i];
            let y = cnt[j];
            if (x < y) [x, y] = [y, x];
            res += mx(1, x - y)
        } else {
            res++;
        }
    }
    pr(res)
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i][1], input[i + 1]);
            i += 2;
        }
    });
};

main()

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}
function getValue() {
  return parseInt(readline());
}
let mod = BigInt(1e9 + 7);
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, m] = iInpArr();
    let arr = iInpArr();
    let obj = {};
    for (let i = 0; i < n; i++) {
      if (obj[arr[i] % m]) obj[arr[i] % m]++;
      else obj[arr[i] % m] = 1;
    }
    let cnt = 0,
      i = 1,
      j = m - 1;
    while (i <= j) {
      if (obj[i] && obj[j]) {
        if (obj[i] === obj[j]) cnt++;
        else if (obj[i] > obj[j]) cnt += obj[i] - (obj[j] + 1) + 1;
        else cnt += obj[j] - (obj[i] + 1) + 1;
      } else if (obj[i]) cnt += obj[i];
      else if (obj[j]) cnt += obj[j];
      i++;
      j--;
    }
    if (obj[0]) cnt++;
    console.log(cnt);
  }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

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

function main() {
  const x = readline();
  //
  Array(parseInt(x)).fill(1).map((t, iii) => {
    // var n = parseInt(readline())
    var [n, m] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });
    var count = {}
    var a = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });
    var answer = 0
    for (let i = 0; i < n; i++) {
      if (!count[a[i] % m]) count[a[i] % m] = 0
      count[a[i] % m]++
    }
    var mark = {}
    Object.keys(count).map(x => {
      x = parseInt(x)
      if (x === 0) {
        answer += 1
        return
      }
      if (x === m - x) {
        answer += 1
        return;
      }
      if (mark[x] || mark[m - x]) return;
      var dif = Math.abs((count[m - x] ? count[m - x] : 0) - count[x])

      // console.log(dif, x, m - x, count[x], count[m - x])
      if (dif <= 1) {
        answer += 1
      } else {
        answer += dif
      }
      mark[x] = true
      mark[m - x] = true
    })

    console.log(answer)
    // console.log(count)
  });

}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var M = nextInt();
		var list = nextIntArray(N);
		var map = {};
		for(var j = 0; j < N; j++){
			var p = list[j] % M;
			if(map[p] == null){
				map[p] = 0;
			}
			map[p]++;
		}
		var output = 0;
		var keys = Object.keys(map);
		var used = new Set();
		for(var j = 0; j < keys.length; j++){
			if(keys[j] == 0){
				if(map[keys[j]] > 0){
					output++;
				}
			}else if(M % 2 == 0 && keys[j] == M / 2){
				if(map[keys[j]] > 0){
					output++;
				}
			}else{
				var L = myconv(keys[j], 1);
				var R = M - L;
				if(map[L] != null && map[R] != null){
					if(used.has(L) || used.has(R)){
						continue;
					}
					used.add(L);
					used.add(R);
					output++;
					if(Math.abs(map[L] - map[R]) > 1){
						output += Math.max(map[L], map[R]) - Math.min(map[L], map[R]) - 1;
					}
				}else{
					if(map[L] != null){
						output += map[L];
					}else{
						output += map[R];
					}
				}
			}
		}
		myout(output);
	}
}

function getInt(num){
    return parseInt(num, 10)
}

var t = parseInt(readline(), 10);

for(var i = 0; i<t; i++){
    var line = readline().split(' ').map(getInt);
    var n = line[0];
    var m = line[1];
    var innerLine = readline().split(' ').map(getInt);
    print(solution(innerLine, m));
}
function solution(arr, m, n){
    var mods = {};
    var result = 0;
    if(m === 1 || n === 1){
        return 1;
    }
    arr.forEach(function(item){
        var mod = item % m;
        mods[mod] = (mods[mod] || 0) + 1;
    });

    if(mods[0]){
        result++;
    }

    var maxInd = Math.floor(((m - 1)/2));
    for(var i = 1; i <= maxInd; i++){
        var a = mods[i] || 0;
        var b = mods[m-i] || 0;
        if(a || b){
            result += Math.max(Math.abs(b - a), 1);
        }
    }

    if((m%2 === 0 ) && (mods[maxInd + 1])){
        result++;
    }
    return result;

}

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

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

function main () {
	let t = rn();
	while (t--) {
		let [n, m] = rna();
		let a = rna();

		let cnt = Array(m);
		for (elm of a)
			cnt[elm % m]++;

		let ans = 0;
		for (let i = 0; i < m; i++) {
			if (cnt[i]) {
				if (2 * i % m == 0) {
					ans++;
					continue;
				}
				ans1 = Math.max(0, cnt[i] - Math.min(cnt[i], cnt[m-i]) - 1);
				ans2 = Math.max(0, cnt[m-i] - Math.min(cnt[i], cnt[m-i]) - 1);
				ans += 1 + ans1 + ans2;
				cnt[i] = cnt[m-i] = 0;
			}
		}
		console.log(ans);
	}
}

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

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

function main () {
	let t = rn();
	while (t--) {
		let [n, m] = rna();
		let a = rna();

		let cnt = Array(m + 1).fill(0);
		for (x of a)
			cnt[x % m]++;

		let ans = 0;
		for (let i = 0; i < m; i++) {
			if (cnt[i]){
				if (i == 0 || i == m - i) {
					ans++;
					continue;
				}
				cnt[i] = Math.max(0, cnt[i] - Math.min(cnt[i], cnt[m-i]) - 1);
				cnt[m-i] = Math.max(0, cnt[m-i] - Math.min(cnt[i], cnt[m-i]) - 1);
				ans += 1 + cnt[i] + cnt[m-i];
				cnt[i] = cnt[m-i] = 0;
			}
		}

		console.log(ans);
	}
}

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

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

function main () {
	let t = rn();
	while (t--) {
		let [n, m] = rna();
		let a = rna();

		let cnt = Array(m + 1).fill(0);
		for (x of a)
			cnt[x % m]++;

		let ans = 0;
		for (let i = 0; i < m; i++) {
			if (cnt[i]){
				if (i == 0) {
					ans++;
					continue;
				}
				cnt[i] = Math.max(0, cnt[i] - Math.min(cnt[i], cnt[m-i]) - 1);
				cnt[m-i] = Math.max(0, cnt[m-i] - Math.min(cnt[i], cnt[m-i]) - 1);
				ans += 1 + cnt[i] + cnt[m-i];
				cnt[i] = cnt[m-i] = 0;
			}
		}

		console.log(ans);
	}
}

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

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

function main () {
	let t = rn();
	while (t--) {
		let [n, m] = rna();
		let a = rna();

		let cnt = Array(m + 1).fill(0);
		for (x of a)
			cnt[x % m]++;

		let ans = 0;
		for (let i = 0; i < m; i++) {
			if (cnt[i]){
				if (Math.abs(cnt[i] - cnt[m-i]) <= 1) {
					cnt[m-i] = 0;
				}
				ans++;
			}
		}

		console.log(ans);
	}
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}
function getValue() {
  return parseInt(readline());
}
let mod = BigInt(1e9 + 7);
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, m] = iInpArr();
    let arr = iInpArr();
    let obj = {};
    for (let i = 0; i < n; i++) arr[i] = arr[i] % m;
    let arr1 = [];
    for (let i = 0; i < n; i++) if (arr[i] !== 0) arr1.push(arr[i]);
    if (arr1.length === 0) {
      console.log(1);
      continue;
    }
    let cnt = 0;
    if (arr1.length === n) cnt = 0;
    else cnt = 1;
    arr1.sort((a, b) => a - b);
    for (let i = 0; i < arr1.length; i++) {
      if (obj[arr1[i]]) obj[arr1[i]].push(i);
      else obj[arr1[i]] = [i];
    }
    let bool = new Array(arr1.length).fill(true);
    for (let i = 0; i < n; i++) {
      if (bool[i]) {
        let t = m - arr1[i];
        obj[arr1[i]].shift();
        while (obj[t]) {
          if (obj[t].length === 0) break;
          bool[obj[t].shift()] = false;
          t = m - t;
        }
        cnt++;
      }
    }
    console.log(cnt);
  }
};
solve();

function getInt(num){
    return parseInt(num, 10)
}

var t = parseInt(readline(), 10);

for(var i = 0; i<t; i++){
    var line = readline().split(' ').map(getInt);
    var n = line[0];
    var m = line[1];
    var innerLine = readline().split(' ').map(getInt);
    print(solution(innerLine, m));
}
function solution(arr, m, n){
    var mods = {};
    var result = 0;
    if(m === 1 || n === 1){
        return 1;
    }
    arr.forEach(function(item){
        var mod = item % m;
        mods[mod] = (mods[item] || 0) + 1;
    });

    if(mods[0]){
        result++;
    }

    var maxInd = Math.floor(((m - 1)/2));
    for(var i = 1; i <= maxInd; i++){
        var a = mods[i] || 0;
        var b = mods[m-i] || 0;
        if(a || b){
            result += Math.max(Math.abs(b - a), 1);
        }
    }

    if((m%2 === 0 ) && (mods[maxInd + 1])){
        result++;
    }
    return result;

}