You are given $$$n$$$ arrays $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$; each array consists of exactly $$$m$$$ integers. We denote the $$$y$$$-th element of the $$$x$$$-th array as $$$a_{x, y}$$$.You have to choose two arrays $$$a_i$$$ and $$$a_j$$$ ($$$1 \le i, j \le n$$$, it is possible that $$$i = j$$$). After that, you will obtain a new array $$$b$$$ consisting of $$$m$$$ integers, such that for every $$$k \in [1, m]$$$ $$$b_k = \max(a_{i, k}, a_{j, k})$$$.Your goal is to choose $$$i$$$ and $$$j$$$ so that the value of $$$\min \limits_{k = 1}^{m} b_k$$$ is maximum possible.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$1 \le m \le 8$$$) — the number of arrays and the number of elements in each array, respectively.
Then $$$n$$$ lines follow, the $$$x$$$-th line contains the array $$$a_x$$$ represented by $$$m$$$ integers $$$a_{x, 1}$$$, $$$a_{x, 2}$$$, ..., $$$a_{x, m}$$$ ($$$0 \le a_{x, y} \le 10^9$$$).

Print two integers $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$, it is possible that $$$i = j$$$) — the indices of the two arrays you have to choose so that the value of $$$\min \limits_{k = 1}^{m} b_k$$$ is maximum possible. If there are multiple answers, print any of them.

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

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

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

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

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

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

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

function main(input) {
  const [n, m] = readInts(input, 0)

  const arrays = new Array(n)
  for(let i = 0; i < n; i++) {
    arrays[i] = readInts(input, i + 1)
  }
  // wr(arrays)

  let l = 0
  let r = 10 ** 9
  let arr1, arr2
  arr1 = arr2 = -1
  while(r - l >= 2) {
    let m = Math.floor((l + r) / 2)
    if(can(m)) l = m
    else r = m
  }
  can(l)
  can(r)

  wr(arr1 + 1, arr2 + 1)
  function can(x) {
    const m21 = 1 << m
    const masks = new Array(m21).fill(-1)

    for(let i = 0; i < n; i++) {
      let msk = 0
      for(let j = 0; j < m; j++) {
        if(arrays[i][j] >= x) msk ^= (1 << j)
      }
      masks[msk] = i
    }

    if(masks[m21 - 1] != -1) {
      arr1 = masks[m21 - 1]
      arr2 = masks[m21 - 1]
      return true
    }

    for(let i = 0; i < m21; i++) {
      for(let j = 0; j < m21; j++) {
        if(masks[i] != -1 && masks[j] != -1 && (i | j) == m21 - 1){
          arr1 = masks[i]
          arr2 = masks[j]
          return true
        }
      }
    }

    return false
  }
}


There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

/**
 *  10.12 night
 *  https://codeforces.com/problemset/problem/6/E
 *
 *  reference:
 *  https://codeforces.com/problemset/status/6/problem/E/page/46?order=BY_PROGRAM_LENGTH_ASC
 *  https://codeforces.com/problemset/submission/6/94367599
 */

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

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

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

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

function gcd(a, b) {
    while (b) [a, b] = [b, a % b];
    return a;
}

function mul(a, b, m) {
    return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}

function pow(a, n, m) {
    let r = 1;
    while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
    return r;
}

let MOD = 998244353;

function inv(b) {
    for (let a = MOD, u = 0, v = 1, t; b; v = t)
        (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
    return (u + MOD) % MOD;
}

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

function main() {
    let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
        out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max,
        abs = Math.abs;

    let [n, k] = $(2), h = $(n), tree = new AVLTree();
    tree.insert(h[0]);
    let Max = 1;
    let allRes = [];
    let i = 0, j = 0;
    while (i < n) {
        while (j < n) {
            j++;
            if (!h[j]) break;
            tree.insert(h[j]);
            if (tree.max() - tree.min() > k) break;
        }
        if (Max < j - i) {
            Max = j - i;
            allRes = [(i + 1) + ' ' + j];
        } else if (Max == j - i) {
            allRes.push((i + 1) + ' ' + j);
        }
        Max = max(j - i, Max);
        tree.remove(h[i++]);
        while (tree.max() - tree.min() > k) {
            tree.remove(h[i++]);
        }
    }
    log(Max, allRes.length);
    log(allRes.join('\n'));
}

let AVLTree = (function () {
    function print(root, printNode) {
        if (printNode === void 0) printNode = function (n) {
            return n.key;
        };

        let out = [];
        row(root, '', true, function (v) {
            return out.push(v);
        }, printNode);
        return out.join('');
    }

    function isBalanced(root) {
        if (root === null) {
            return true;
        }
        let lh = height(root.left);
        let rh = height(root.right);
        if (Math.abs(lh - rh) <= 1 &&
            isBalanced(root.left) &&
            isBalanced(root.right)) {
            return true;
        }
        return false;
    }

    function height(node) {
        return node ? (1 + Math.max(height(node.left), height(node.right))) : 0;
    }

    function loadRecursive(parent, keys, values, start, end) {
        let size = end - start;
        if (size > 0) {
            let middle = start + Math.floor(size / 2);
            let key = keys[middle];
            let data = values[middle];
            let node = { key: key, data: data, parent: parent };
            node.left = loadRecursive(node, keys, values, start, middle);
            node.right = loadRecursive(node, keys, values, middle + 1, end);
            return node;
        }
        return null;
    }

    function markBalance(node) {
        if (node === null) {
            return 0;
        }
        let lh = markBalance(node.left);
        let rh = markBalance(node.right);

        node.balanceFactor = lh - rh;
        return Math.max(lh, rh) + 1;
    }

    function sort(keys, values, left, right, compare) {
        if (left >= right) {
            return;
        }
        let pivot = keys[(left + right) >> 1];
        let i = left - 1;
        let j = right + 1;
        while (true) {
            do {
                i++;
            } while (compare(keys[i], pivot) < 0);
            do {
                j--;
            } while (compare(keys[j], pivot) > 0);
            if (i >= j) {
                break;
            }
            let tmp = keys[i];
            keys[i] = keys[j];
            keys[j] = tmp;

            tmp = values[i];
            values[i] = values[j];
            values[j] = tmp;
        }

        sort(keys, values, left, j, compare);
        sort(keys, values, j + 1, right, compare);
    }

    function DEFAULT_COMPARE(a, b) {
        return a > b ? 1 : a < b ? -1 : 0;
    }

    function rotateLeft(node) {
        let rightNode = node.right;
        node.right = rightNode.left;

        if (rightNode.left) {
            rightNode.left.parent = node;
        }

        rightNode.parent = node.parent;
        if (rightNode.parent) {
            if (rightNode.parent.left === node) {
                rightNode.parent.left = rightNode;
            } else {
                rightNode.parent.right = rightNode;
            }
        }

        node.parent = rightNode;
        rightNode.left = node;

        node.balanceFactor += 1;
        if (rightNode.balanceFactor < 0) {
            node.balanceFactor -= rightNode.balanceFactor;
        }

        rightNode.balanceFactor += 1;
        if (node.balanceFactor > 0) {
            rightNode.balanceFactor += node.balanceFactor;
        }
        return rightNode;
    }

    function rotateRight(node) {
        let leftNode = node.left;
        node.left = leftNode.right;
        if (node.left) {
            node.left.parent = node;
        }

        leftNode.parent = node.parent;
        if (leftNode.parent) {
            if (leftNode.parent.left === node) {
                leftNode.parent.left = leftNode;
            } else {
                leftNode.parent.right = leftNode;
            }
        }

        node.parent = leftNode;
        leftNode.right = node;

        node.balanceFactor -= 1;
        if (leftNode.balanceFactor > 0) {
            node.balanceFactor -= leftNode.balanceFactor;
        }

        leftNode.balanceFactor -= 1;
        if (node.balanceFactor < 0) {
            leftNode.balanceFactor += node.balanceFactor;
        }

        return leftNode;
    }

    let AVLTree = function AVLTree(comparator, noDuplicates) {
        if (noDuplicates === void 0) noDuplicates = false;

        this._comparator = comparator || DEFAULT_COMPARE;
        this._root = null;
        this._size = 0;
        this._noDuplicates = !!noDuplicates;
    };

    let prototypeAccessors = { size: { configurable: true } };

    AVLTree.prototype.destroy = function destroy() {
        return this.clear();
    };

    AVLTree.prototype.clear = function clear() {
        this._root = null;
        this._size = 0;
        return this;
    };

    prototypeAccessors.size.get = function () {
        return this._size;
    };

    AVLTree.prototype.contains = function contains(key) {
        if (this._root) {
            let node = this._root;
            let comparator = this._comparator;
            while (node) {
                let cmp = comparator(key, node.key);
                if (cmp === 0) {
                    return true;
                } else if (cmp < 0) {
                    node = node.left;
                } else {
                    node = node.right;
                }
            }
        }
        return false;
    };

    AVLTree.prototype.next = function next(node) {
        let successor = node;
        if (successor) {
            if (successor.right) {
                successor = successor.right;
                while (successor.left) {
                    successor = successor.left;
                }
            } else {
                successor = node.parent;
                while (successor && successor.right === node) {
                    node = successor;
                    successor = successor.parent;
                }
            }
        }
        return successor;
    };

    AVLTree.prototype.prev = function prev(node) {
        let predecessor = node;
        if (predecessor) {
            if (predecessor.left) {
                predecessor = predecessor.left;
                while (predecessor.right) {
                    predecessor = predecessor.right;
                }
            } else {
                predecessor = node.parent;
                while (predecessor && predecessor.left === node) {
                    node = predecessor;
                    predecessor = predecessor.parent;
                }
            }
        }
        return predecessor;
    };

    AVLTree.prototype.forEach = function forEach(callback) {
        let current = this._root;
        let s = [], done = false, i = 0;
        while (!done) {
            if (current) {
                s.push(current);
                current = current.left;
            } else {
                if (s.length > 0) {
                    current = s.pop();
                    callback(current, i++);
                    current = current.right;
                } else {
                    done = true;
                }
            }
        }
        return this;
    };

    AVLTree.prototype.range = function range(low, high, fn, ctx) {
        let this$1 = this;
        let Q = [];
        let compare = this._comparator;
        let node = this._root, cmp;
        while (Q.length !== 0 || node) {
            if (node) {
                Q.push(node);
                node = node.left;
            } else {
                node = Q.pop();
                cmp = compare(node.key, high);
                if (cmp > 0) {
                    break;
                } else if (compare(node.key, low) >= 0) {
                    if (fn.call(ctx, node)) {
                        return this$1;
                    }
                }
                node = node.right;
            }
        }
        return this;
    };

    AVLTree.prototype.keys = function keys() {
        let current = this._root;
        let s = [], r = [], done = false;
        while (!done) {
            if (current) {
                s.push(current);
                current = current.left;
            } else {
                if (s.length > 0) {
                    current = s.pop();
                    r.push(current.key);
                    current = current.right;
                } else {
                    done = true;
                }
            }
        }
        return r;
    };

    AVLTree.prototype.values = function values() {
        let current = this._root;
        let s = [], r = [], done = false;
        while (!done) {
            if (current) {
                s.push(current);
                current = current.left;
            } else {
                if (s.length > 0) {
                    current = s.pop();
                    r.push(current.data);
                    current = current.right;
                } else {
                    done = true;
                }
            }
        }
        return r;
    };

    AVLTree.prototype.at = function at(index) {
        let current = this._root;
        let s = [], done = false, i = 0;
        while (!done) {
            if (current) {
                s.push(current);
                current = current.left;
            } else {
                if (s.length > 0) {
                    current = s.pop();
                    if (i === index) {
                        return current;
                    }
                    i++;
                    current = current.right;
                } else {
                    done = true;
                }
            }
        }
        return null;
    };

    AVLTree.prototype.minNode = function minNode() {
        let node = this._root;
        if (!node) {
            return null;
        }
        while (node.left) {
            node = node.left;
        }
        return node;
    };

    AVLTree.prototype.maxNode = function maxNode() {
        let node = this._root;
        if (!node) {
            return null;
        }
        while (node.right) {
            node = node.right;
        }
        return node;
    };

    AVLTree.prototype.min = function min() {
        let node = this._root;
        if (!node) {
            return null;
        }
        while (node.left) {
            node = node.left;
        }
        return node.key;
    };

    AVLTree.prototype.max = function max() {
        let node = this._root;
        if (!node) {
            return null;
        }
        while (node.right) {
            node = node.right;
        }
        return node.key;
    };

    AVLTree.prototype.isEmpty = function isEmpty() {
        return !this._root;
    };

    AVLTree.prototype.pop = function pop() {
        let node = this._root, returnValue = null;
        if (node) {
            while (node.left) {
                node = node.left;
            }
            returnValue = { key: node.key, data: node.data };
            this.remove(node.key);
        }
        return returnValue;
    };

    AVLTree.prototype.find = function find(key) {
        let root = this._root;
        let subtree = root, cmp;
        let compare = this._comparator;
        while (subtree) {
            cmp = compare(key, subtree.key);
            if (cmp === 0) {
                return subtree;
            } else if (cmp < 0) {
                subtree = subtree.left;
            } else {
                subtree = subtree.right;
            }
        }

        return null;
    };

    AVLTree.prototype.insert = function insert(key, data) {
        let this$1 = this;
        if (!this._root) {
            this._root = {
                parent: null, left: null, right: null, balanceFactor: 0,
                key: key, data: data
            };
            this._size++;
            return this._root;
        }

        let compare = this._comparator;
        let node = this._root;
        let parent = null;
        let cmp = 0;

        if (this._noDuplicates) {
            while (node) {
                cmp = compare(key, node.key);
                parent = node;
                if (cmp === 0) {
                    return null;
                } else if (cmp < 0) {
                    node = node.left;
                } else {
                    node = node.right;
                }
            }
        } else {
            while (node) {
                cmp = compare(key, node.key);
                parent = node;
                if (cmp <= 0) {
                    node = node.left;
                } //return null;
                else {
                    node = node.right;
                }
            }
        }

        let newNode = {
            left: null,
            right: null,
            balanceFactor: 0,
            parent: parent, key: key, data: data
        };
        let newRoot;
        if (cmp <= 0) {
            parent.left = newNode;
        } else {
            parent.right = newNode;
        }

        while (parent) {
            cmp = compare(parent.key, key);
            if (cmp < 0) {
                parent.balanceFactor -= 1;
            } else {
                parent.balanceFactor += 1;
            }

            if (parent.balanceFactor === 0) {
                break;
            } else if (parent.balanceFactor < -1) {
                if (parent.right.balanceFactor === 1) {
                    rotateRight(parent.right);
                }
                newRoot = rotateLeft(parent);
                if (parent === this$1._root) {
                    this$1._root = newRoot;
                }
                break;
            } else if (parent.balanceFactor > 1) {
                if (parent.left.balanceFactor === -1) {
                    rotateLeft(parent.left);
                }
                newRoot = rotateRight(parent);

                if (parent === this$1._root) {
                    this$1._root = newRoot;
                }
                break;
            }
            parent = parent.parent;
        }

        this._size++;
        return newNode;
    };

    AVLTree.prototype.remove = function remove(key) {
        let this$1 = this;
        if (!this._root) {
            return null;
        }
        let node = this._root;
        let compare = this._comparator;
        let cmp = 0;
        while (node) {
            cmp = compare(key, node.key);
            if (cmp === 0) {
                break;
            } else if (cmp < 0) {
                node = node.left;
            } else {
                node = node.right;
            }
        }
        if (!node) {
            return null;
        }

        let returnValue = node.key;
        let max, min;

        if (node.left) {
            max = node.left;

            while (max.left || max.right) {
                while (max.right) {
                    max = max.right;
                }

                node.key = max.key;
                node.data = max.data;
                if (max.left) {
                    node = max;
                    max = max.left;
                }
            }

            node.key = max.key;
            node.data = max.data;
            node = max;
        }

        if (node.right) {
            min = node.right;

            while (min.left || min.right) {
                while (min.left) {
                    min = min.left;
                }

                node.key = min.key;
                node.data = min.data;
                if (min.right) {
                    node = min;
                    min = min.right;
                }
            }

            node.key = min.key;
            node.data = min.data;
            node = min;
        }

        let parent = node.parent;
        let pp = node;
        let newRoot;

        while (parent) {
            if (parent.left === pp) {
                parent.balanceFactor -= 1;
            } else {
                parent.balanceFactor += 1;
            }

            if (parent.balanceFactor < -1) {
                if (parent.right.balanceFactor === 1) {
                    rotateRight(parent.right);
                }
                newRoot = rotateLeft(parent);

                if (parent === this$1._root) {
                    this$1._root = newRoot;
                }
                parent = newRoot;
            } else if (parent.balanceFactor > 1) {
                if (parent.left.balanceFactor === -1) {
                    rotateLeft(parent.left);
                }
                newRoot = rotateRight(parent);
                if (parent === this$1._root) {
                    this$1._root = newRoot;
                }
                parent = newRoot;
            }
            if (parent.balanceFactor === -1 || parent.balanceFactor === 1) {
                break;
            }
            pp = parent;
            parent = parent.parent;
        }

        if (node.parent) {
            if (node.parent.left === node) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
        }

        if (node === this._root) {
            this._root = null;
        }

        this._size--;
        return returnValue;
    };

    AVLTree.prototype.load = function load(keys, values, presort) {
        if (keys === void 0) keys = [];
        if (values === void 0) values = [];

        if (this._size !== 0) {
            throw new Error('bulk-load: tree is not empty');
        }
        let size = keys.length;
        if (presort) {
            sort(keys, values, 0, size - 1, this._comparator);
        }
        this._root = loadRecursive(null, keys, values, 0, size);
        markBalance(this._root);
        this._size = size;
        return this;
    };

    AVLTree.prototype.isBalanced = function isBalanced$1() {
        return isBalanced(this._root);
    };

    AVLTree.prototype.toString = function toString(printNode) {
        return print(this._root, printNode);
    };

    Object.defineProperties(AVLTree.prototype, prototypeAccessors);

    AVLTree.default = AVLTree;

    return AVLTree;

})();


You are given a sequence of positive integers a1,a2,...,an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).

The first line contains the integer n (2≤n≤2·10^5). The second line contains elements of the sequence a1,a2,...,an (1≤ai≤1000). All the elements are positive integers.

Print on the first line the number of the sought indices. Print on the second line the sought indices in the increasing order. All indices are integers from 1 to n.
If the sought elements do not exist, then the first output line should contain number 0. In this case you may either not print the second line or print an empty line.

private fun readInt() = readString().toInt()
private fun readString() = readLine().toString()
private fun readDouble() = readString().toDouble()
private fun readListString() = readString().split(" ")
private fun readListInt() = readString().split(" ").map { it.toInt() }

fun main() {

    readInt()
    val nums = readListInt()
    var sum = 0L
    for (n in nums)
        sum += n
    val ans = mutableListOf<Int>()
    for (i in 0 until nums.size) {
        val left = sum - nums[i]
        if (left / (nums.size - 1) == nums[i].toLong() && nums[i]*(nums.size-1L)==left) {
            ans.add(i + 1)
        }
    }
    println(ans.size)
    if (ans.isNotEmpty()) {
        println(ans.joinToString(" "))
    }

}


Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1≤n≤100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1≤xi,yi≤1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

import java.io.*

/**
 * https://codeforces.com/problemset/problem/217/A
 *
 * # Complexity and Explanation
 *
 * * Time: O(n*log(n))
 * * Space: O(n)
 */
private class DisjointSets {
  private val parents = mutableMapOf<Position, Position>()
  private val ranks = mutableMapOf<Position, Int>()

  var groupCount = 0
    private set

  val positions get() = parents.keys

  operator fun plusAssign(pos: Position) {
    if (pos in parents) return

    parents += pos to pos
    ranks += pos to 0
    groupCount++
  }

  fun union(u: Position, v: Position): Position {
    var smallRep = find(u)
    var bigRep = find(v)
    if (smallRep == bigRep) return bigRep

    if (ranks[smallRep] > ranks[bigRep]) {
      smallRep = bigRep.also { bigRep = smallRep }
    }

    parents[smallRep] = bigRep
    if (ranks[smallRep] == ranks[bigRep]) ranks[bigRep] = ranks[bigRep]!! + 1
    groupCount--
    return bigRep
  }

  fun find(u: Position): Position {
    if (u != parents[u]) {
      parents[u] = find(parents[u]!!)
    }

    return parents[u]!!
  }
}

private data class Position(
  val x: Int,
  val y: Int,
)

private var debugMode: Boolean = false

fun start(
  inStream: InputStream = System.`in`,
  outStream: OutputStream? = null,
  debugModeEnabled: Boolean = false
) {
  debugMode = debugModeEnabled

  useWith(outStream.toPrintStream()) {
    useWith(inStream.bufferedReader(Charsets.ISO_8859_1)) {
      val nPositions = nextLine.toInt()
      val ds = DisjointSets()

      repeat(nPositions) {
        val (x, y) = nextLine.toInts()
        val pos = Position(x, y)
        ds += pos
      }

      val horReps = mutableMapOf<Int, Position>()
      val verReps = mutableMapOf<Int, Position>()
      for (pos in ds.positions) {
        val horRep = horReps[pos.x]
        horReps[pos.x] = if (horRep == null) {
          pos
        } else {
          // merge new position to horRep
          ds.union(pos, horRep)
        }

        val verRep = verReps[pos.y]
        verReps[pos.y] = if (verRep == null) {
          pos
        } else {
          // merge new position to verRep
          ds.union(pos, verRep)
        }
      }

      print(ds.groupCount - 1)
    }
  }
}

/************************************************/

/**
 * * `bufferedReader(Charsets.ISO_8859_1)` is faster than `bufferedReader()`
 * * `bufferedReader()` is faster than `readLine()`
 * * `readLine()` is faster than `Scanner`.
 *   Note: `readLine()` doesn't work well with older kotlin versions on some
 *   competitive programming platforms, such as spoj.com.
 * * See more
 *   * https://kotlinlang.org/docs/competitive-programming.html
 *   * https://stackoverflow.com/a/41283570/8228301
 */
fun main() = start()

private inline fun <T : Closeable?, R> useWith(
  receiver: T,
  block: T.() -> R
) = receiver.use(block)

private val spacesRegex = Regex("""[\s\n\r]+""")

private fun String.toWords() = split(spacesRegex)

private fun String.toInts() = toWords().map(String::toInt)

private fun String.toUInts() = toWords().map(String::toUInt)

private fun String.toLongs() = toWords().map(String::toLong)

private fun String.toULongs() = toWords().map(String::toULong)

private fun String.toDoubles() = toWords().map(String::toDouble)

private val BufferedReader.nextLineOrNull get() = readLine()?.trim()

private val BufferedReader.nextLine get() = readLine()!!.trim()

// private fun <T> nextSequence(n: Int): Sequence<T> {
// }
//
// private fun nextCharMatrix(rows: Int, cols: Int): Array<CharArray> {
// }
//
// private fun nextIntMatrix(rows: Int, cols: Int): Array<IntArray> {
// }
//
// private fun nextLongMatrix(rows: Int, cols: Int): Array<LongArray> {
// }

private fun PrintStream.print(separator: String, vararg values: String?) =
  values.forEachIndexed { index, value ->
    print(if (index == 0) value else "$separator$value")
  }

private fun PrintStream.println(separator: String, vararg values: String?) =
  print(separator, *values).also { println() }

private fun OutputStream?.toPrintStream() =
  this?.let(::PrintStream) ?: System.out

private operator fun <T : Comparable<T>> T?.compareTo(other: T?) =
  compareValues(this, other)

// private fun <T : Comparable<T>> T?.nullsFirstCompareTo(other: T?) =
//   compareValues(this, other)

private infix fun <T : Comparable<T>> T?.nullsLastCompareTo(other: T?) = when {
  this === other -> 0
  this == null -> 1
  other == null -> -1
  else -> this.compareTo(other)
}

// private infix fun <T : Comparable<T>> T?.`?lt`(other: T?) =
//   nullsFirstCompareTo(other) < 0
//
// private infix fun <T : Comparable<T>> T?.`?gt`(other: T?) =
//   nullsFirstCompareTo(other) > 0
//
// private infix fun <T : Comparable<T>> T?.`?lte`(other: T?) =
//   nullsFirstCompareTo(other) <= 0
//
// private infix fun <T : Comparable<T>> T?.`?gte`(other: T?) =
//   nullsFirstCompareTo(other) >= 0

private infix fun <T : Comparable<T>> T?.`lt?`(other: T?) =
  nullsLastCompareTo(other) < 0

private infix fun <T : Comparable<T>> T?.`gt?`(other: T?) =
  nullsLastCompareTo(other) > 0

private infix fun <T : Comparable<T>> T?.`lte?`(other: T?) =
  nullsLastCompareTo(other) <= 0

private infix fun <T : Comparable<T>> T?.`gte?`(other: T?) =
  nullsLastCompareTo(other) >= 0

private fun <T> IndexedValue<T>.toPair() = index to value

/**
 * You can remove this function if running on kotlin 1.4+
 *
 * See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/remove-last.html
 */
private fun <T> MutableList<T>.removeLast() =
  if (isEmpty())
    throw NoSuchElementException("List is empty.")
  else removeAt(lastIndex)

/**
 * You can remove this function if running on kotlin 1.4+
 *
 * See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/remove-last-or-null.html
 */
private fun <T> MutableList<T>.removeLastOrNull(): T? =
  if (isEmpty()) null else removeAt(lastIndex)


We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not.

The first line contains a single positive integer, n (1≤n≤10^5), showing how many numbers are in the array. The next line contains n space-separated integers xi (1≤xi≤10^12).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier.

Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't.

The given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO".

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

fun main() = with(BufferedReader(InputStreamReader(System.`in`))) {
    var sb: StringBuilder = StringBuilder()
    var n: Int = readLine().toInt()
    var primes: BooleanArray = BooleanArray(1000001)

    primes[0] = true
    primes[1] = true

    for (i in 2..1000000) {
        if (!primes[i]) {
            for (j in i * 2..1000000 step (i)) {
                primes[j] = true
            }
        }
    }

    fun square(n: Long): Int {
        var sqrtN = Math.sqrt(n.toDouble())
        if (sqrtN == sqrtN.toInt().toDouble()) {
            return 1;
        } else {
            return 0;
        }
    }

    var st: StringTokenizer = StringTokenizer(readLine())
    while (st.hasMoreTokens()) {
        var cur: Long = st.nextToken().toLong();
        if (cur == 4L) {
            sb.append("YES")
        } else if (cur % 2 == 0L) {
            sb.append("NO")
        } else if (!primes[Math.sqrt(cur.toDouble())
                .toInt()] && square(cur) == 1
        ) {
            sb.append("YES")
        } else {
            sb.append("NO")
        }
        sb.append('\n')
    }
    println(sb)
}


Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.

The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The number of letters in each genome doesn't exceed 10^5. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.

Print "YES", if the dwarves belong to the same race. Otherwise, print "NO".

First example: you can simply swap two letters in string "ab". So we get "ba".  Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b".

//  A. Comparing Strings

// region Preamble

import java.util.concurrent.ConcurrentHashMap
import kotlin.math.*

// IO
val reader = System.`in`.bufferedReader()
val writer = System.out.bufferedWriter()

fun readLn(): String = reader.readLine()
fun readInt() = readLn().toInt()
fun readLong() = readLn().toLong()
fun readDouble() = readLn().toDouble()
fun readWords() = readLn().split(" ")
fun readInts() = readWords().map { it.toInt() }
fun readLongs() = readWords().map { it.toLong() }
fun readDoubles() = readWords().map { it.toDouble() }
fun readLines(n: Int) = List(n) { readLn() }

fun Boolean.yesNo() = if (this) "YES" else "NO"
fun writeLn(s: String) = writer.write("$s\n")

@JvmName("writeLn1")
fun String.writeLn() = writer.write("\n")

// Functional
fun List<Int>.cumulativeSum1() = runningFold(0) { x, y -> x + y }
fun List<Int>.cumulativeSum() = cumulativeSum1().drop(1)

@JvmName("cumulativeSum1Long")
fun List<Long>.cumulativeSum1() = runningFold(0L) { x, y -> x + y }

@JvmName("cumulativeSumLong")
fun List<Long>.cumulativeSum() = cumulativeSum1().drop(1)

fun <E> List<E>.isDistinct() = size == toSet().size

fun <T> List<T>.histogram() = groupingBy { it }.eachCount().withDefault { 0 }
fun String.histogram() = groupingBy { it }.eachCount().withDefault { 0 }

fun <T> List<T>.groupContiguous(): List<List<T>> {
  val groups = mutableListOf<MutableList<T>>()
  forEach { e ->
    if (e == groups.lastOrNull()?.lastOrNull()) {
      groups.last().add(e)
    } else {
      groups.add(mutableListOf(e))
    }
  }
  return groups
}

fun <T> permutationsWithReplacement(input: Set<T>, n: Int): List<List<T>> =
  if (n <= 0) listOf(emptyList())
  else input.flatMap { first ->
    permutationsWithReplacement(input, n - 1).map { rest ->
      listOf(first) + rest
    }
  }

fun <T> permutations(input: Set<T>): List<List<T>> {
  if (input.isEmpty()) return listOf(emptyList())

  val first = input.first()
  val tail = input.drop(1).toSet()

  return permutations(tail).flatMap { rest ->
    (0..rest.size).map {
      buildList {
        addAll(rest.take(it))
        add(first)
        addAll(rest.drop(it))
      }
    }
  }
}

fun <T> combinations(input: Set<T>, n: Int): Set<Set<T>> {
  if (n <= 0) return setOf(emptySet())
  if (input.isEmpty()) return emptySet()

  val first = input.take(1).toSet()
  val tail = input.drop(1).toSet()

  return combinations(tail, n - 1).map { rest -> first + rest }.toSet() + combinations(tail, n)
}

// Math
fun Int.isOdd() = this % 2 == 1
fun Long.isOdd() = this % 2 == 1L
fun Int.isEven() = !isOdd()
fun Long.isEven() = !isOdd()
fun Int.isZero() = this == 0
fun Long.isZero() = this == 0L
fun Int.isPositive() = this > 0
fun Long.isPositive() = this > 0L
fun Int.isNegative() = this < 0
fun Long.isNegative() = this < 0L
fun Int.isPositiveOrZero() = this >= 0
fun Long.isPositiveOrZero() = this >= 0L
fun Int.isNegativeOrZero() = this <= 0
fun Long.isNegativeOrZero() = this <= 0L

infix fun Int.divides(o: Int) = o % this == 0
infix fun Long.divides(o: Long) = o % this == 0L
infix fun Int.divisibleBy(o: Int) = o divides this
infix fun Long.divisibleBy(o: Long) = o divides this

infix fun Int.floorDiv(o: Int) = floor(toDouble() / o).toInt()
infix fun Long.floorDiv(o: Long) = floor(toDouble() / o).toInt()
infix fun Int.ceilDiv(o: Int) = ceil(toDouble() / o).toInt()
infix fun Long.ceilDiv(o: Long) = ceil(toDouble() / o).toInt()

infix fun Int.mod(m: Int) = ((this % m) + m) % m
infix fun Long.mod(m: Long) = ((this % m) + m) % m

// Number Theory
fun primeSieve(n: Int): List<Boolean> {
  val s = BooleanArray(n + 1) { true }
  val limit = sqrt(n.toDouble()).toInt()
  (2..limit).forEach { i ->
    if (s[i]) (i * i..n).forEach { j -> s[j] = false }
  }
  return s.toList()
}

fun primes(n: Int) = primeSieve(n).mapIndexedNotNull { i, p -> i.takeIf { p } }

// DP
inline fun <I, O> memoize(crossinline fn: (I) -> O): ((I) -> O) = with(ConcurrentHashMap<I, O>()) {
  { input -> get(input) ?: fn(input).also { output -> set(input, output) } }
}
// endregion

fun solve(p: String, q: String): Boolean {
  if (p.length != q.length)
    return false
  val m = p.zip(q).withIndex().filter { (_, v) -> v.first != v.second }.map { it.index }
  if (m.size != 2)
    return false
  val (i, j) = m
  return p[i] == q[j] && p[j] == q[i]
}

fun main() {
  val (p, q) = readLines(2)
  println(solve(p, q).yesNo())
}

[{'input': ['ab\r\nba\r\n'], 'output': ['YES\r\n']}, {'input': ['aa\r\nab\r\n'], 'output': ['NO\r\n']}, {'input': ['a\r\nza\r\n'], 'output': ['NO\r\n']}, {'input': ['vvea\r\nvvae\r\n'], 'output': ['YES\r\n']}, {'input': ['rtfabanpc\r\natfabrnpc\r\n'], 'output': ['YES\r\n']}, {'input': ['mt\r\ntm\r\n'], 'output': ['YES\r\n']}, {'input': ['qxolmbkkt\r\naovlajmlf\r\n'], 'output': ['NO\r\n']}, {'input': ['b\r\ng\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\naba\r\n'], 'output': ['NO\r\n']}, {'input': ['ba\r\na\r\n'], 'output': ['NO\r\n']}, {'input': ['a\r\nab\r\n'], 'output': ['NO\r\n']}, {'input': ['a\r\naa\r\n'], 'output': ['NO\r\n']}, {'input': ['a\r\nz\r\n'], 'output': ['NO\r\n']}, {'input': ['aabb\r\nbbaa\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\nbd\r\n'], 'output': ['NO\r\n']}, {'input': ['bac\r\ndae\r\n'], 'output': ['NO\r\n']}, {'input': ['abc\r\nakl\r\n'], 'output': ['NO\r\n']}, {'input': ['cb\r\naa\r\n'], 'output': ['NO\r\n']}, {'input': ['abaab\r\naabba\r\n'], 'output': ['NO\r\n']}, {'input': ['aab\r\naaa\r\n'], 'output': ['NO\r\n']}, {'input': ['abcde\r\nedcba\r\n'], 'output': ['NO\r\n']}, {'input': ['abab\r\nbaba\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\nbac\r\n'], 'output': ['NO\r\n']}, {'input': ['abcd\r\naqcb\r\n'], 'output': ['NO\r\n']}, {'input': ['abc\r\nbad\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\nca\r\n'], 'output': ['NO\r\n']}, {'input': ['abc\r\nab\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\nbae\r\n'], 'output': ['NO\r\n']}, {'input': ['aaaabcccca\r\naaaadccccb\r\n'], 'output': ['NO\r\n']}, {'input': ['acaa\r\nabca\r\n'], 'output': ['NO\r\n']}, {'input': ['aba\r\naab\r\n'], 'output': ['YES\r\n']}, {'input': ['ah\r\nla\r\n'], 'output': ['NO\r\n']}, {'input': ['aab\r\naa\r\n'], 'output': ['NO\r\n']}, {'input': ['abab\r\nabcd\r\n'], 'output': ['NO\r\n']}, {'input': ['ed\r\nab\r\n'], 'output': ['NO\r\n']}]


Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1≤i≤n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.

The first line contains two space-separated integers s and n (1≤s≤10^4, 1≤n≤10^3). Then n lines follow: the i-th line contains space-separated integers xi and yi (1≤xi≤10^4, 0≤yi≤10^4) — the i-th dragon's strength and the bonus for defeating it.

On a single line print "YES" (without the quotes), if Kirito can move on to the next level and print "NO" (without the quotes), if he can't.

In the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2+99=101. Now he can defeat the second dragon and move on to the next level.
In the second sample Kirito's strength is too small to defeat the only dragon and win.

import java.io.BufferedInputStream
import java.io.PrintWriter
import java.util.UUID
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow

fun main() {
    solve()
}

fun solve() {
    var (s, n) = getIntLine(2)
    val list = mutableListOf<Pair<Int, Int>>()
    repeat(n) {
        list.add(Pair(getIntFast, getIntFast))
    }
    list.sortBy { it.first }
    list.forEach {
        if (s > it.first) s += it.second
        else {
            println("NO")
            return
        }
    }
    println("YES")
}

tailrec fun gcd(a: Int, b: Int): Int {
    if(b == 0) return a
    return if (a % b == 0) abs(b) else gcd(b, a % b)
}

val getIntFast: Int get() = Reader.nextInt()
val getLong: Long get() = Reader.nextLong()
val getString: String get() = Reader.nextString()
fun getLongLine(n: Int) = LongArray(n) { getLong }
fun getIntLine(n: Int) = IntArray(n) { getIntFast }
infix fun Int.pow(other: Int) = toDouble().pow(other.toDouble()).toInt()

object Reader {
    private const val BS = 1 shl 16
    private const val NC = 0.toChar()
    private val buf = ByteArray(BS)
    private var bId = 0
    private var size = 0
    private var c = NC

    private var IN: BufferedInputStream = BufferedInputStream(System.`in`, BS)
    val OUT: PrintWriter = PrintWriter(System.out)

    private val char: Char
        get() {
            while (bId == size) {
                size = IN.read(buf) // no need for checked exceptions
                if (size == -1) return NC
                bId = 0
            }
            return buf[bId++].toInt().toChar()
        }

    fun nextInt(): Int {
        var neg = false
        if (c == NC) c = char
        while (c < '0' || c > '9') {
            if (c == '-') neg = true
            c = char
        }
        var res = 0
        while (c in '0'..'9') {
            res = (res shl 3) + (res shl 1) + (c - '0')
            c = char
        }
        return if (neg) -res else res
    }

    fun nextLong(): Long {
        var neg = false
        if (c == NC) c = char
        while (c < '0' || c > '9') {
            if (c == '-') neg = true
            c = char
        }
        var res = 0L
        while (c in '0'..'9') {
            res = (res shl 3) + (res shl 1) + (c - '0')
            c = char
        }
        return if (neg) -res else res
    }

    fun nextString(): String {
        val ret = StringBuilder()
        while (true) {
            c = char
            if (!isWhitespace(c)) {
                break
            }
        }
        ret.append(c)
        while (true) {
            c = char
            if (isWhitespace(c)) {
                break
            }
            ret.append(c)
        }
        return ret.toString()
    }

    private fun isWhitespace(c: Char): Boolean {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t'
    }
}


Valera had two bags of potatoes, the first of these bags contains x (x≥1) potatoes, and the second — y (y≥1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x+y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.

The first line of input contains three integers y, k, n (1≤y,k,n≤10^9;  ≤10^5).

Print the list of whitespace-separated integers — all possible values of x in ascending order. You should print each possible value of x exactly once.
If there are no such values of x print a single integer -1.

//  A. Two Bags of Potatoes

// region Preamble

import java.util.concurrent.ConcurrentHashMap
import kotlin.math.*

// IO
val reader = System.`in`.bufferedReader()
val writer = System.out.bufferedWriter()

fun readLn(): String = reader.readLine()
fun readInt() = readLn().toInt()
fun readLong() = readLn().toLong()
fun readDouble() = readLn().toDouble()
fun readWords() = readLn().split(" ")
fun readInts() = readWords().map { it.toInt() }
fun readLongs() = readWords().map { it.toLong() }
fun readDoubles() = readWords().map { it.toDouble() }
fun readLines(n: Int) = List(n) { readLn() }

fun Boolean.yesNo() = if (this) "YES" else "NO"
fun writeLn(s: String) = writer.write("$s\n")

@JvmName("writeLn1")
fun String.writeLn() = writer.write("$this\n")

// Functional
fun List<Int>.cumulativeSum1() = scan(0) { x, y -> x + y }
fun List<Int>.cumulativeSum() = cumulativeSum1().drop(1)

@JvmName("cumulativeSum1Long")
fun List<Long>.cumulativeSum1() = scan(0L) { x, y -> x + y }

@JvmName("cumulativeSumLong")
fun List<Long>.cumulativeSum() = cumulativeSum1().drop(1)

fun <E> List<E>.isDistinct() = size == toSet().size

fun <T> List<List<T>>.transpose(): List<List<T>> = List(minOf { it.size }) { i -> map { it[i] } }

fun <T> List<T>.histogram() = groupingBy { it }.eachCount().withDefault { 0 }
fun String.histogram() = groupingBy { it }.eachCount().withDefault { 0 }

fun <T> List<T>.groupContiguous(): List<List<T>> {
  val groups = mutableListOf<MutableList<T>>()
  forEach { e ->
    if (e == groups.lastOrNull()?.lastOrNull()) {
      groups.last().add(e)
    } else {
      groups.add(mutableListOf(e))
    }
  }
  return groups
}

fun <T> permutationsWithReplacement(input: Set<T>, n: Int): List<List<T>> =
  if (n <= 0) listOf(emptyList())
  else input.flatMap { first ->
    permutationsWithReplacement(input, n - 1).map { rest ->
      listOf(first) + rest
    }
  }

fun <T> permutations(input: Set<T>): List<List<T>> {
  if (input.isEmpty()) return listOf(emptyList())

  val first = input.first()
  val tail = input.drop(1).toSet()

  return permutations(tail).flatMap { rest ->
    (0..rest.size).map {
      buildList {
        addAll(rest.take(it))
        add(first)
        addAll(rest.drop(it))
      }
    }
  }
}

fun <T> combinations(input: Set<T>, n: Int): Set<Set<T>> {
  if (n <= 0) return setOf(emptySet())
  if (input.isEmpty()) return emptySet()

  val first = input.take(1).toSet()
  val tail = input.drop(1).toSet()

  return combinations(tail, n - 1).map { rest -> first + rest }.toSet() + combinations(tail, n)
}

// Math
fun Int.isOdd() = this % 2 == 1
fun Long.isOdd() = this % 2 == 1L
fun Int.isEven() = !isOdd()
fun Long.isEven() = !isOdd()
fun Int.isZero() = this == 0
fun Long.isZero() = this == 0L
fun Int.isPositive() = this > 0
fun Long.isPositive() = this > 0L
fun Int.isNegative() = this < 0
fun Long.isNegative() = this < 0L
fun Int.isPositiveOrZero() = this >= 0
fun Long.isPositiveOrZero() = this >= 0L
fun Int.isNegativeOrZero() = this <= 0
fun Long.isNegativeOrZero() = this <= 0L

infix fun Int.divides(o: Int) = o % this == 0
infix fun Long.divides(o: Long) = o % this == 0L
infix fun Int.divisibleBy(o: Int) = o divides this
infix fun Long.divisibleBy(o: Long) = o divides this

infix fun Int.floorDiv(o: Int) = floor(toDouble() / o).toInt()
infix fun Long.floorDiv(o: Long) = floor(toDouble() / o).toInt()
infix fun Int.ceilDiv(o: Int) = ceil(toDouble() / o).toInt()
infix fun Long.ceilDiv(o: Long) = ceil(toDouble() / o).toInt()

infix fun Int.mod(m: Int) = ((this % m) + m) % m
infix fun Long.mod(m: Long) = ((this % m) + m) % m

// Number Theory
fun primeSieve(n: Int): List<Boolean> {
  val s = BooleanArray(n + 1) { true }
  val limit = sqrt(n.toDouble()).toInt()
  (2..limit).forEach { i ->
    if (s[i]) (i * i..n).forEach { j -> s[j] = false }
  }
  return s.toList()
}

fun primes(n: Int) = primeSieve(n).mapIndexedNotNull { i, p -> i.takeIf { p } }

// DP
inline fun <I, O> memoize(crossinline fn: (I) -> O): ((I) -> O) = with(ConcurrentHashMap<I, O>()) {
  { input -> get(input) ?: fn(input).also { output -> set(input, output) } }
}
// endregion

fun main() {
  val (y, k, n) = readInts()
  val r = (k .. n  step k).filter { it > y }
  if (r.isEmpty()) {
    writeLn("-1")
  } else {
    r.joinToString(" ") { "${it - y}" }.writeLn()
  }
  writer.flush()
}


A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li,ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a,b] covers segment [c,d], if they meet this condition a≤c≤d≤b.

The first line contains integer n (1≤n≤10^5) — the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li,ri (1≤li≤ri≤10^9) — the borders of the i-th segment.
It is guaranteed that no two segments coincide.

Print a single integer — the number of the segment that covers all other segments in the set. If there's no solution, print -1.
The segments are numbered starting from 1 in the order in which they appear in the input.

//  B. Big Segment

// region Preamble

import java.util.concurrent.ConcurrentHashMap
import kotlin.math.*

// IO
val reader = System.`in`.bufferedReader()
val writer = System.out.bufferedWriter()

fun readLn(): String = reader.readLine()
fun readInt() = readLn().toInt()
fun readLong() = readLn().toLong()
fun readDouble() = readLn().toDouble()
fun readWords() = readLn().split(" ")
fun readInts() = readWords().map { it.toInt() }
fun readLongs() = readWords().map { it.toLong() }
fun readDoubles() = readWords().map { it.toDouble() }
fun readLines(n: Int) = List(n) { readLn() }

fun Boolean.yesNo() = if (this) "YES" else "NO"
fun writeLn(s: String) = writer.write("$s\n")

@JvmName("writeLn1")
fun String.writeLn() = writer.write("\n")

// Functional
fun List<Int>.cumulativeSum1() = runningFold(0) { x, y -> x + y }
fun List<Int>.cumulativeSum() = cumulativeSum1().drop(1)

@JvmName("cumulativeSum1Long")
fun List<Long>.cumulativeSum1() = runningFold(0L) { x, y -> x + y }

@JvmName("cumulativeSumLong")
fun List<Long>.cumulativeSum() = cumulativeSum1().drop(1)

fun <E> List<E>.isDistinct() = size == toSet().size

fun <T> List<T>.histogram() = groupingBy { it }.eachCount().withDefault { 0 }
fun String.histogram() = groupingBy { it }.eachCount().withDefault { 0 }

fun <T> List<T>.groupContiguous(): List<List<T>> {
  val groups = mutableListOf<MutableList<T>>()
  forEach { e ->
    if (e == groups.lastOrNull()?.lastOrNull()) {
      groups.last().add(e)
    } else {
      groups.add(mutableListOf(e))
    }
  }
  return groups
}

fun <T> permutationsWithReplacement(input: Set<T>, n: Int): List<List<T>> =
  if (n <= 0) listOf(emptyList())
  else input.flatMap { first ->
    permutationsWithReplacement(input, n - 1).map { rest ->
      listOf(first) + rest
    }
  }

fun <T> permutations(input: Set<T>): List<List<T>> {
  if (input.isEmpty()) return listOf(emptyList())

  val first = input.first()
  val tail = input.drop(1).toSet()

  return permutations(tail).flatMap { rest ->
    (0..rest.size).map {
      buildList {
        addAll(rest.take(it))
        add(first)
        addAll(rest.drop(it))
      }
    }
  }
}

fun <T> combinations(input: Set<T>, n: Int): Set<Set<T>> {
  if (n <= 0) return setOf(emptySet())
  if (input.isEmpty()) return emptySet()

  val first = input.take(1).toSet()
  val tail = input.drop(1).toSet()

  return combinations(tail, n - 1).map { rest -> first + rest }.toSet() + combinations(tail, n)
}

// Math
fun Int.isOdd() = this % 2 == 1
fun Long.isOdd() = this % 2 == 1L
fun Int.isEven() = !isOdd()
fun Long.isEven() = !isOdd()
fun Int.isZero() = this == 0
fun Long.isZero() = this == 0L
fun Int.isPositive() = this > 0
fun Long.isPositive() = this > 0L
fun Int.isNegative() = this < 0
fun Long.isNegative() = this < 0L
fun Int.isPositiveOrZero() = this >= 0
fun Long.isPositiveOrZero() = this >= 0L
fun Int.isNegativeOrZero() = this <= 0
fun Long.isNegativeOrZero() = this <= 0L

infix fun Int.divides(o: Int) = o % this == 0
infix fun Long.divides(o: Long) = o % this == 0L
infix fun Int.divisibleBy(o: Int) = o divides this
infix fun Long.divisibleBy(o: Long) = o divides this

infix fun Int.floorDiv(o: Int) = floor(toDouble() / o).toInt()
infix fun Long.floorDiv(o: Long) = floor(toDouble() / o).toInt()
infix fun Int.ceilDiv(o: Int) = ceil(toDouble() / o).toInt()
infix fun Long.ceilDiv(o: Long) = ceil(toDouble() / o).toInt()

infix fun Int.mod(m: Int) = ((this % m) + m) % m
infix fun Long.mod(m: Long) = ((this % m) + m) % m

// Number Theory
fun primeSieve(n: Int): List<Boolean> {
  val s = BooleanArray(n + 1) { true }
  val limit = sqrt(n.toDouble()).toInt()
  (2..limit).forEach { i ->
    if (s[i]) (i * i..n).forEach { j -> s[j] = false }
  }
  return s.toList()
}

fun primes(n: Int) = primeSieve(n).mapIndexedNotNull { i, p -> i.takeIf { p } }

// DP
inline fun <I, O> memoize(crossinline fn: (I) -> O): ((I) -> O) = with(ConcurrentHashMap<I, O>()) {
  { input -> get(input) ?: fn(input).also { output -> set(input, output) } }
}
// endregion

fun main() {
  val n = readInt()
  val segments = readLines(n).map { it.split(" ").map { it.toInt() } }
  val mn = segments.minOf { it.first() }
  val mx = segments.maxOf { it.last() }
  val sg = listOf(mn, mx)
  val r = segments.indexOf(sg)
  println(if (r >= 0) r + 1 else r)
}


The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.

The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 10^5 digits.

In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.

In the first sample the best strategy is to delete the second digit. That results in number 112=310.
In the second sample the best strategy is to delete the third or fourth digits — that results in number 110102=2610.

fun main() {
  val a = readln().trim()
  val r = if ('0' in a) {
    val i = a.indexOf('0')
    a.take(i) + a.drop(i+1)
  } else {
    a.drop(1)
  }
  println(r)
}


Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Roma's got n positive integers. He wonders, how many of those integers have not more than k lucky digits? Help him, write the program that solves the problem.

The first line contains two integers n, k (1≤n,k≤100). The second line contains n integers ai (1≤ai≤10^9) — the numbers that Roma has.
The numbers in the lines are separated by single spaces.

In a single line print a single integer — the answer to the problem.

In the first sample all numbers contain at most four lucky digits, so the answer is 3.
In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2.

fun main() {
    val c = readln().split(" ")
    val k = c[1].toInt()
    val s = readln().split(" ")
    var r = 0
    for (i in s.indices)
    {
        val t = s[i]
        var c = 0
        for (j in t.indices)
        {
            if (t[j] == '4' || t[j] == '7') c++
        }
        if (c <= k) r++
    }
    println(r)
}


There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that:  Alice will get $$$a$$$ ($$$a > 0$$$) candies;  Betty will get $$$b$$$ ($$$b > 0$$$) candies;  each sister will get some integer number of candies;  Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$);  all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$) — the number of candies you have.

For each test case, print the answer — the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.

NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are:  $$$a=6$$$, $$$b=1$$$;  $$$a=5$$$, $$$b=2$$$;  $$$a=4$$$, $$$b=3$$$.

fun main() {
    val r = System.`in`.bufferedReader()
    val s = StringBuilder()
    repeat(r.readLine()!!.toInt()){
        val n = r.readLine()!!.toInt()
        when{
            n == 1 || n ==2 -> {
                println(0)}
            else -> println((n+1)/2-1)
        }
    }
}


The Duck songFor simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen: Andrew, Dmitry and Michal should eat at least $$$x$$$, $$$y$$$ and $$$z$$$ grapes, respectively. Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only. On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes. Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with $$$a$$$ green grapes, $$$b$$$ purple grapes and $$$c$$$ black grapes.However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?It is not required to distribute all the grapes, so it's possible that some of them will remain unused.

The first line contains three integers $$$x$$$, $$$y$$$ and $$$z$$$ ($$$1 \le x, y, z \le 10^5$$$) — the number of grapes Andrew, Dmitry and Michal want to eat. The second line contains three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a, b, c \le 10^5$$$) — the number of green, purple and black grapes in the box.

If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".

NoteIn the first example, there is only one possible distribution:Andrew should take $$$1$$$ green grape, Dmitry should take $$$3$$$ remaining green grapes and $$$3$$$ purple grapes, and Michal will take $$$2$$$ out of $$$3$$$ available black grapes.In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(

  fun main(args:Array<String>){
    val (a, b, c) = readLine()!!.split(' ')
    var x1:Int = a.toInt()
    var y1:Int = b.toInt()
    var z1:Int = c.toInt()
    val (a1, b1, c1) = readLine()!!.split(' ')
    var x:Int = a1.toInt()
    var y:Int = b1.toInt()
    var z:Int = c1.toInt()
    var flag = 0
    if(x1 <= x && flag == 0) {x -= x1}
    else {flag = 1}

    if(y1 <= (y + x) && flag == 0)
        {
            if(y1 <= y) y -= y1
            else {
                x -= (y1 - y)
                y = 0
            }
        }
    else {flag = 1}

    if(z1 <= (x + y + z) && flag == 0) {flag = 0}
    else { flag = 1}

    if(flag == 0) {println("YES")}
    else {println("NO")}
}


Ania has a large integer $$$S$$$. Its decimal representation has length $$$n$$$ and doesn't contain any leading zeroes. Ania is allowed to change at most $$$k$$$ digits of $$$S$$$. She wants to do it in such a way that $$$S$$$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — the number of digits in the decimal representation of $$$S$$$ and the maximum allowed number of changed digits. The second line contains the integer $$$S$$$. It's guaranteed that $$$S$$$ has exactly $$$n$$$ digits and doesn't contain any leading zeroes.

Output the minimal possible value of $$$S$$$ which Ania can end with. Note that the resulting integer should also have $$$n$$$ digits.

NoteA number has leading zeroes if it consists of at least two digits and its first digit is $$$0$$$. For example, numbers $$$00$$$, $$$00069$$$ and $$$0101$$$ have leading zeroes, while $$$0$$$, $$$3000$$$ and $$$1010$$$ don't have leading zeroes.

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single long
private fun readStrings() = readLn().split(" ") // list of strings

private fun readInts() = readStrings().map { it.toInt() } // list of ints
private fun readLongs() = readStrings().map { it.toLong() } // list of Longs

var n = 0

fun main() {

    var (n, k) = readInts()

    val s = readLine()!!

    val sb = StringBuilder()

    if (s.length == 1){
        if (k > 0){
            print("0")
        } else {
            print(s)
        }
        return
    }

    for ((i, c) in s.withIndex()) {
        if (k == 0) {
            sb.append(c)
            continue
        }

        if (i == 0) {
            if (c != '1') {
                sb.append('1')
                k--
            } else {
                sb.append(c)
            }
        } else if (c != '0') {
            k--
            sb.append('0')
        } else {
            sb.append(c)
        }
    }

    print(sb)
}


Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.The committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color.Unfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color $$$x$$$ such that there are currently at least two puppies of color $$$x$$$ and recolor all puppies of the color $$$x$$$ into some arbitrary color $$$y$$$. Luckily, this operation can be applied multiple times (including zero).For example, if the number of puppies is $$$7$$$ and their colors are represented as the string "abababc", then in one operation Slava can get the results "zbzbzbc", "bbbbbbc", "aaaaaac", "acacacc" and others. However, if the current color sequence is "abababc", then he can't choose $$$x$$$='c' right now, because currently only one puppy has the color 'c'.Help Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of puppies. The second line contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters, where the $$$i$$$-th symbol denotes the $$$i$$$-th puppy's color.

If it's possible to recolor all puppies into one color, print "Yes". Otherwise print "No". Output the answer without quotation signs.

NoteIn the first example Slava can perform the following steps:   take all puppies of color 'a' (a total of two) and recolor them into 'b';  take all puppies of color 'd' (a total of two) and recolor them into 'c';  take all puppies of color 'b' (three puppies for now) and recolor them into 'c'. In the second example it's impossible to recolor any of the puppies.In the third example all the puppies' colors are the same; thus there's no need to recolor anything.

fun main() {
    val t = readLine()!!.toInt()
    val z = readLine()!!.toCharArray()
    val sett = z.toHashSet()
    if (sett.size == t && t > 1)
    {
      println("No")
    }else{
      println("Yes")
    }
  }


Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:  on this day the gym is closed and the contest is not carried out;  on this day the gym is closed and the contest is carried out;  on this day the gym is open and the contest is not carried out;  on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 3) separated by space, where:    ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;  ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;  ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;  ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.

Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:   to do sport on any two consecutive days,  to write the contest on any two consecutive days.

NoteIn the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.

// compile : kotlinc newyear.kt -include-runtime -d test.jar
// run : java -jar test.jar

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints

fun main()
{
	// var state = Array(4,{0})
	var dp = Array(105,{IntArray(4)})

	var n = readInt()
	var arr = readInts()
	// arr = readInts()

	for(i in 1..n)
		for(j in 0..2)
			dp[i][j] = 1000000
	for(i in 0..2)
		dp[0][i] = 0
	for(i in 1..n)
	{
		var r = arr[i-1]
		// println("${r} ${dp[i][0]} ${dp[i][1]} ${dp[i][2]}")
		dp[i][0] = 1+minOf(dp[i-1][0],dp[i-1][1],dp[i-1][2])
		if(r==1)
			dp[i][1] = minOf(dp[i-1][0],dp[i-1][2])
		if(r==2)
			dp[i][2] = minOf(dp[i-1][0],dp[i-1][1])
		if(r==3)
		{
			dp[i][1] = minOf(dp[i-1][0],dp[i-1][2])
			dp[i][2] = minOf(dp[i-1][0],dp[i-1][1])
		}
		// println("${r} ${dp[i][0]} ${dp[i][1]} ${dp[i][2]}")
	}

	var res = minOf(dp[n][0],dp[n][1],dp[n][2])
	println("${res}")
}


The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:    Elements of the main diagonal.   Elements of the secondary diagonal.   Elements of the "middle" row — the row which has exactly  rows above it and the same number of rows below it.   Elements of the "middle" column — the column that has exactly  columns to the left of it and the same number of columns to the right of it.    The figure shows a 5 × 5 matrix.   The good elements are marked with green.  Help the Smart Beaver count the sum of good elements of the given matrix.

The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are:    1 ≤ n ≤ 5  The input limitations for getting 100 points are:   1 ≤ n ≤ 101

Print a single integer — the sum of good matrix elements.

NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.

/* http://codeforces.com/problemset/problem/177/A1 */

fun main() {
    val n = readLine()!!.toInt()
    val matrix = Array(n) { Array(n) { 0 } }
    for (i in 0 until n) {
        matrix[i] = readLine()!!.split(" ").map { it.toInt() }.toTypedArray()
    }
    val middleRowSum = matrix[n / 2].sum()
    val middleColumnSum = matrix.map { row -> row[n / 2] }.sum()
    val primaryDiagSum = matrix.mapIndexed { rowIndex, row -> row[rowIndex] }.sum()
    val secondaryDiagSum = matrix.mapIndexed { rowIndex, row -> row[n - rowIndex - 1] }.sum()
    val centerCell = matrix[n / 2][n / 2]
    println(middleRowSum + middleColumnSum + primaryDiagSum + secondaryDiagSum - 3 * centerCell)
}


Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

fun main() {
    val input = readLine()!!
    val size = input.toCharArray().distinct().size
    val desired = readLine()!!.toInt()
    if (desired > input.length) {
        println("impossible")
    } else {
        val ans = (desired - size).coerceAtLeast(0)
        println(ans)
    }
}

[{'input': 'yandex\r\n6\r\n', 'output': ['0\r\n']}, {'input': 'yahoo\r\n5\r\n', 'output': ['1\r\n']}, {'input': 'google\r\n7\r\n', 'output': ['impossible\r\n']}, {'input': 'a\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'z\r\n2\r\n', 'output': ['impossible\r\n']}, {'input': 'fwgfrwgkuwghfiruhewgirueguhergiqrbvgrgf\r\n26\r\n', 'output': ['14\r\n']}, {'input': 'nfevghreuoghrueighoqghbnebvnejbvnbgneluqe\r\n26\r\n', 'output': ['12\r\n']}, {'input': 'a\r\n3\r\n', 'output': ['impossible\r\n']}, {'input': 'smaxpqplaqqbxuqxalqmbmmgubbpspxhawbxsuqhhegpmmpebqmqpbbeplwaepxmsahuepuhuhwxeqmmlgqubuaxehwuwasgxpqmugbmuawuhwqlswllssueglbxepbmwgs\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'cuguccgcugcugucgggggcgcgucgucugcuuuccccuugccg\r\n4\r\n', 'output': ['1\r\n']}, {'input': 'fcfccfcfccfcfcffcffffffcfccfccfcffccccfcffffccfccfcffcfcccccffcfffcccffcfccfffffcccfccffffffccfccccf\r\n20\r\n', 'output': ['18\r\n']}, {'input': 'swmkwaruyv\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'tnbqpsuhkczmejirvyfdolxwga\r\n22\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abb\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'aaaa\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'yandex\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'aaabbbccc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'asdfgh\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'aab\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'mynameissako\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abcdef\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'abcdefg\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'abc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'asdafjsgljdllgjdgkl\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'yaay\r\n3\r\n', 'output': ['1\r\n']}, {'input': 'yaay\r\n4\r\n', 'output': ['2\r\n']}, {'input': 'zzzzzz\r\n2\r\n', 'output': ['1\r\n']}]


Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

import kotlin.math.max

fun main() {
    val numRecords = readLine()!!.toInt()
    var sol = 0
    val regNumbers = mutableSetOf<String>()
    for (i in 1..numRecords) {
        val (action, regNumber) = readLine()!!.split(" ")
        if (action == "+")
            regNumbers.add(regNumber)
        else {
            if (regNumber in regNumbers) {
                sol = max(sol, regNumbers.size)
                regNumbers.remove(regNumber)
            } else {
                sol = max(sol + 1, regNumbers.size + 1)
            }
        }
    }
    sol = max(sol, regNumbers.size)
    print(sol)
}


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

import java.io.*
import java.util.*

fun dif(a: Int, b: Int) : Int {
  val x = a - b
  return (if (x / 10 == 0) 0 else 1) + (if (x % 10 == 0) 0 else 1)
}

fun solve(start: Int, end: Int, num: Int) : Int {
  var minDif = 3
  var minv = -1
  for (i in start..end) {
    var d = dif(i, num)
    if (d < minDif) {
      minDif = d
      minv = i
    }
  }
  return minv
}

fun main(args : Array<String>) {
//  val fin = Scanner(File("a.in"))
  val fin = Scanner(System.`in`)
  val form = fin.nextInt()
  val sh = if (form == 12) 1 else 0
  val eh = if (form == 12) 12 else 23
  val sm = 0
  val em = 59
  val str = fin.next()
  val hours = str.substring(0, 2).toInt()
  val mins = str.substring(3, 5).toInt()
  print("%02d".format(solve(sh, eh, hours)))
  print(":")
  print("%02d".format(solve(sm, em, mins)))
  fin.close()
}


Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

import java.util.*

fun main() {

    val sc = Scanner(System.`in`)
    val n : Int = sc.nextInt()
    val s : CharArray = sc.next().toCharArray()
    var count = 0

    for (i in 0 until n) {
        if (s[i] == 'R') {
            for (j in (i + 1) until n) {
                if (s[j] == 'L') {
                    for (k in i..j) s[k] = 'x'
                    if ((j - i) % 2 == 0) count++
                    break
                }
            }
        } else continue
    }

    for (i in 0 until n) {
        if (s[i] == 'L') {
            for (j in 0..i) s[j] = 'x'
            break
        } else if (s[i] == '.') continue
        else break
    }

    for (i in (n - 1) downTo 0) {
        if (s[i] == 'R') {
            for (j in (n - 1) downTo i) s[j] = 'x'
            break
        } else if (s[i] == '.') continue
        else break
    }

    for (i in 0 until n)
        if (s[i] == '.')
            count++

    print(count)

}


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

import java.util.*

fun main() {
    val scanner = Scanner(System.`in`)
    val input = scanner.nextInt()

    val countList = MutableList(input) {n -> false}
    var currentCount = 0
    var result = 0

    while (scanner.hasNext()) {
        val nextNum = scanner.nextInt()

        if (currentCount == input) {
            break
        }
        currentCount++

        if (nextNum > input) {
            result++
        } else {
            if (countList[nextNum - 1]) {
                result++
            } else {
                countList[nextNum - 1] = true
            }
        }

        if (result == input) {
            break
        } else {
            continue
        }
    }

    println(result)
}


One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.

Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).

NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".

import java.io.*
import java.util.*

fun <T : Comparable<T>> max(a: T, b: T): T = if (b > a) b else a
fun <T : Comparable<T>> min(a: T, b: T): T = if (b < a) b else a
fun Number.isEven(): Boolean = if (this.toInt() and 1 == 0) true else false
fun Number.isOdd (): Boolean = !this.isEven()

fun main(args: Array<String>) {
    if (args.isNotEmpty()) System.setIn(FileInputStream(args[0]))
    val br = BufferedReader(InputStreamReader(System.`in`))
    val bw = BufferedWriter(OutputStreamWriter(System.out))

    val st = StringTokenizer(br.readLine())
    val n = st.nextToken().toInt()
    val m = st.nextToken().toInt()
    val arr = Array(n) { CharArray(m) }
    for (i in arr.indices) {
        val st = StringTokenizer(br.readLine())
        arr[i] = st.nextToken().toCharArray()
    }
    val modu = (1e9 + 7).toInt()
    var answer = 1L
    for (i in arr[0].indices) {
        answer *= arr.map { it[i] }.distinct().count()
        answer %= modu
    }

    bw.write("$answer\n")
    bw.close()
}

[{'input': '2 3\r\nAAB\r\nBAA\r\n', 'output': ['4\r\n']}, {'input': '4 5\r\nABABA\r\nBCGDG\r\nAAAAA\r\nYABSA\r\n', 'output': ['216\r\n']}, {'input': '1 1\r\nE\r\n', 'output': ['1\r\n']}, {'input': '2 2\r\nNS\r\nPD\r\n', 'output': ['4\r\n']}, {'input': '3 4\r\nPJKD\r\nNFJX\r\nFGFK\r\n', 'output': ['81\r\n']}, {'input': '4 5\r\nSXFMY\r\nATHLM\r\nKDDQW\r\nZWGDS\r\n', 'output': ['1024\r\n']}, {'input': '20 14\r\nJNFKBBBJYZHWQE\r\nLBOKZCPFNKDBJY\r\nX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PZYE\r\nUZDBFTURYJ\r\nRVSMQTIZGW\r\nWDJQHMIRYY\r\nKCORHQPZYE\r\nRRPLFOZZVY\r\nJTXMFNNNYJ\r\nMVTGGOZZVV\r\nEHAFFNUZVF\r\nLBRNWJZNYE\r\nJVMOHTPZYJ\r\nWTARFJLZVV\r\nLVJCWOURVW\r\nLCLQFJYRVV\r\nQVBVGNJRYF\r\nNTZGHOLRYE\r\nMGQKHOUPYJ\r\nRRSSBXPZYJ\r\nRYCRGTLZYJ\r\nJRDEGNKRVW\r\nRZKFGHYRVG\r\nMDJBFNIZYG\r\nMPLWHXIZYE\r\nSRZMHMURVE\r\nMTEBBMRZYJ\r\nJPJIFOLZYM\r\n', 'output': ['919913906\r\n']}, {'input': '40 7\r\nPNTVVER\r\nPAHTQDR\r\nRXMJVAS\r\nVIQNLYC\r\nILPUSVX\r\nYJOXQDJ\r\nSEFODTO\r\nOTJMREL\r\nLIQRZGD\r\nLBJJPOR\r\nRUTYHQO\r\nRIWEPBD\r\nKQUMFIB\r\nISTRRYH\r\nXBTOTGK\r\nRFQODEY\r\nHDSTZTP\r\nYCXFAGL\r\nAREGRFU\r\nLELZUYU\r\nGVABDKH\r\nFJAMMME\r\nACVULXE\r\nJHVPJAS\r\nAAQNMBX\r\nJJGUCXG\r\nOQATILQ\r\nNEOSHJM\r\nHFLWOFM\r\nICYEQHY\r\nFACGLYP\r\nPLLXJEQ\r\nDCHXYPB\r\nAGDDZJJ\r\nLSQRXTN\r\nHDQZXIY\r\nNAHDDWW\r\nQCMXRQN\r\nFDUDSZO\r\nHKBEVTW\r\n', 'output': ['206575993\r\n']}, {'input': '2 2\r\nAA\r\nBB\r\n', 'output': ['4\r\n']}, {'input': '1 10\r\nAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '2 8\r\nAAAAAAAA\r\nBBBBBBBB\r\n', 'output': ['256\r\n']}, {'input': '10 10\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDD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