Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are $$$n$$$ cards with $$$k$$$ features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with $$$k = 4$$$.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.

The first line of each test contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 1500$$$, $$$1 \le k \le 30$$$) — number of cards and number of features. Each of the following $$$n$$$ lines contains a card description: a string consisting of $$$k$$$ letters "S", "E", "T". The $$$i$$$-th character of this string decribes the $$$i$$$-th feature of that card. All cards are distinct.

Output a single integer — the number of ways to choose three cards that form a set.

NoteIn the third example test, these two triples of cards are sets:  "SETT", "TEST", "EEET"  "TEST", "ESTE", "STES"

function myout(t){print(t);}//standard output
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}
function Main() {
  var tmp = myconv(readline(),4);
  var n = tmp[0];
  var ink = tmp[1];
  var list = [];
  var reqlist = [];
  var inputSet = new Set();
  for(var i = 0; i < n; i++){
      var strin = readline();
      list.push(myconv(strin,6));
      inputSet.add(strin);
  }
  var output = 0;
  for(var i = 0; i < n-1; i++){
      for(var j = i+1; j < n; j++){
          var reqstr = "";
          for(var k = 0; k < ink; k++){
              if(list[i][k] == list[j][k]){
                  reqstr += list[i][k];
              }else{
                  if((list[i][k] == "E" && list[j][k] == "T") ||
                    (list[i][k] == "T" && list[j][k] == "E")){
                      reqstr += "S";
                  }else if((list[i][k] == "S" && list[j][k] == "T") ||
                    (list[i][k] == "T" && list[j][k] == "S")){
                      reqstr += "E";
                  }else{
                      reqstr += "T";
                  }
              }
          }
          if(inputSet.has(reqstr)){
            output++;
          }
      }
  }
  myout(output / 3);
}

Main();

'use strict';

var readline = require('readline');

function nkStdinReader() {
  return new Promise(function (resolve) {
    var stdin = readline.createInterface(process.stdin);
    var output = [];
    var lines;
    stdin.on('line', function (line) {
      output.push(line);

      if (output.length === 1) {
        lines = +line.split(' ')[0];
      } else if (--lines === 0) {
        stdin.close();
        resolve(output);
      }
    });
  });
}

// https://codeforces.com/problemset/problem/1287/B
var setCreator = new Map([['EE', 'E'], ['ES', 'T'], ['ET', 'S'], ['SE', 'T'], ['SS', 'S'], ['ST', 'E'], ['TE', 'S'], ['TS', 'E'], ['TT', 'T']]);

function getSetCard(card1, card2) {
  var card = '';

  for (var x = 0; x < card1.length; x++) {
    card += setCreator.get(card1[x] + card2[x]);
  }

  return card;
}

nkStdinReader().then(function (input) {
  var cards = input.slice(1);
  var cardLookup = new Map(cards.map(function (c, i) {
    return [c, i];
  }));
  var output = 0;

  for (var x = 0; x < cards.length - 2; x++) {
    for (var y = x + 1; y < cards.length - 1; y++) {
      var setCard = getSetCard(cards[x], cards[y]);

      if ((cardLookup.get(setCard) || 0) > y) {
        output++;
      }
    }
  }

  console.log(output);
});

'use strict';

var readline = require('readline');

function nkStdinReader() {
  return new Promise(function (resolve) {
    var stdin = readline.createInterface(process.stdin);
    var output = [];
    var lines;
    stdin.on('line', function (line) {
      output.push(line);

      if (output.length === 1) {
        lines = +line.split(' ')[0];
      } else if (--lines === 0) {
        stdin.close();
        resolve(output);
      }
    });
  });
}

// https://codeforces.com/problemset/problem/1287/B

function getSetCard(card1, card2) {
  var card = '';

  var _loop = function _loop(x) {
    var a = card1[x];
    var b = card2[x];

    if (a === b) {
      card += a;
    } else {
      card += ['E', 'S', 'T'].find(function (c) {
        return c !== a && c !== b;
      });
    }
  };

  for (var x = 0; x < card1.length; x++) {
    _loop(x);
  }

  return card;
}

nkStdinReader().then(function (input) {
  var cards = input.slice(1);
  var cardLookup = new Map(cards.map(function (c, i) {
    return [c, i];
  }));
  var output = 0;

  for (var x = 0; x < cards.length - 2; x++) {
    for (var y = x + 1; y < cards.length - 1; y++) {
      var setCard = getSetCard(cards[x], cards[y]);

      if (cardLookup.get(setCard) || 0 > y) {
        output++;
      }
    }
  }

  console.log(output);
});

'use strict';

var readline = require('readline');

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isFunction(x) {
    return typeof x === 'function';
}
//# sourceMappingURL=isFunction.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var _enable_super_gross_mode_that_will_cause_bad_things = false;
var config = {
    Promise: undefined,
    set useDeprecatedSynchronousErrorHandling(value) {
        if (value) {
            var error = /*@__PURE__*/ new Error();
            /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
        }
        _enable_super_gross_mode_that_will_cause_bad_things = value;
    },
    get useDeprecatedSynchronousErrorHandling() {
        return _enable_super_gross_mode_that_will_cause_bad_things;
    },
};
//# sourceMappingURL=config.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function hostReportError(err) {
    setTimeout(function () { throw err; }, 0);
}
//# sourceMappingURL=hostReportError.js.map

/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */
var empty = {
    closed: true,
    next: function (value) { },
    error: function (err) {
        if (config.useDeprecatedSynchronousErrorHandling) {
            throw err;
        }
        else {
            hostReportError(err);
        }
    },
    complete: function () { }
};
//# sourceMappingURL=Observer.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();
//# sourceMappingURL=isArray.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isObject(x) {
    return x !== null && typeof x === 'object';
}
//# sourceMappingURL=isObject.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {
    function UnsubscriptionErrorImpl(errors) {
        Error.call(this);
        this.message = errors ?
            errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ') : '';
        this.name = 'UnsubscriptionError';
        this.errors = errors;
        return this;
    }
    UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);
    return UnsubscriptionErrorImpl;
})();
var UnsubscriptionError = UnsubscriptionErrorImpl;
//# sourceMappingURL=UnsubscriptionError.js.map

/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */
var Subscription = /*@__PURE__*/ (function () {
    function Subscription(unsubscribe) {
        this.closed = false;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (unsubscribe) {
            this._unsubscribe = unsubscribe;
        }
    }
    Subscription.prototype.unsubscribe = function () {
        var errors;
        if (this.closed) {
            return;
        }
        var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
        this.closed = true;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (_parentOrParents instanceof Subscription) {
            _parentOrParents.remove(this);
        }
        else if (_parentOrParents !== null) {
            for (var index = 0; index < _parentOrParents.length; ++index) {
                var parent_1 = _parentOrParents[index];
                parent_1.remove(this);
            }
        }
        if (isFunction(_unsubscribe)) {
            try {
                _unsubscribe.call(this);
            }
            catch (e) {
                errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
            }
        }
        if (isArray(_subscriptions)) {
            var index = -1;
            var len = _subscriptions.length;
            while (++index < len) {
                var sub = _subscriptions[index];
                if (isObject(sub)) {
                    try {
                        sub.unsubscribe();
                    }
                    catch (e) {
                        errors = errors || [];
                        if (e instanceof UnsubscriptionError) {
                            errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
                        }
                        else {
                            errors.push(e);
                        }
                    }
                }
            }
        }
        if (errors) {
            throw new UnsubscriptionError(errors);
        }
    };
    Subscription.prototype.add = function (teardown) {
        var subscription = teardown;
        if (!teardown) {
            return Subscription.EMPTY;
        }
        switch (typeof teardown) {
            case 'function':
                subscription = new Subscription(teardown);
            case 'object':
                if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
                    return subscription;
                }
                else if (this.closed) {
                    subscription.unsubscribe();
                    return subscription;
                }
                else if (!(subscription instanceof Subscription)) {
                    var tmp = subscription;
                    subscription = new Subscription();
                    subscription._subscriptions = [tmp];
                }
                break;
            default: {
                throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
            }
        }
        var _parentOrParents = subscription._parentOrParents;
        if (_parentOrParents === null) {
            subscription._parentOrParents = this;
        }
        else if (_parentOrParents instanceof Subscription) {
            if (_parentOrParents === this) {
                return subscription;
            }
            subscription._parentOrParents = [_parentOrParents, this];
        }
        else if (_parentOrParents.indexOf(this) === -1) {
            _parentOrParents.push(this);
        }
        else {
            return subscription;
        }
        var subscriptions = this._subscriptions;
        if (subscriptions === null) {
            this._subscriptions = [subscription];
        }
        else {
            subscriptions.push(subscription);
        }
        return subscription;
    };
    Subscription.prototype.remove = function (subscription) {
        var subscriptions = this._subscriptions;
        if (subscriptions) {
            var subscriptionIndex = subscriptions.indexOf(subscription);
            if (subscriptionIndex !== -1) {
                subscriptions.splice(subscriptionIndex, 1);
            }
        }
    };
    Subscription.EMPTY = (function (empty) {
        empty.closed = true;
        return empty;
    }(new Subscription()));
    return Subscription;
}());
function flattenUnsubscriptionErrors(errors) {
    return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);
}
//# sourceMappingURL=Subscription.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var rxSubscriber = /*@__PURE__*/ (function () {
    return typeof Symbol === 'function'
        ? /*@__PURE__*/ Symbol('rxSubscriber')
        : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();
})();
//# sourceMappingURL=rxSubscriber.js.map

/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */
var Subscriber = /*@__PURE__*/ (function (_super) {
    __extends(Subscriber, _super);
    function Subscriber(destinationOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this.syncErrorValue = null;
        _this.syncErrorThrown = false;
        _this.syncErrorThrowable = false;
        _this.isStopped = false;
        switch (arguments.length) {
            case 0:
                _this.destination = empty;
                break;
            case 1:
                if (!destinationOrNext) {
                    _this.destination = empty;
                    break;
                }
                if (typeof destinationOrNext === 'object') {
                    if (destinationOrNext instanceof Subscriber) {
                        _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
                        _this.destination = destinationOrNext;
                        destinationOrNext.add(_this);
                    }
                    else {
                        _this.syncErrorThrowable = true;
                        _this.destination = new SafeSubscriber(_this, destinationOrNext);
                    }
                    break;
                }
            default:
                _this.syncErrorThrowable = true;
                _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
                break;
        }
        return _this;
    }
    Subscriber.prototype[rxSubscriber] = function () { return this; };
    Subscriber.create = function (next, error, complete) {
        var subscriber = new Subscriber(next, error, complete);
        subscriber.syncErrorThrowable = false;
        return subscriber;
    };
    Subscriber.prototype.next = function (value) {
        if (!this.isStopped) {
            this._next(value);
        }
    };
    Subscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            this.isStopped = true;
            this._error(err);
        }
    };
    Subscriber.prototype.complete = function () {
        if (!this.isStopped) {
            this.isStopped = true;
            this._complete();
        }
    };
    Subscriber.prototype.unsubscribe = function () {
        if (this.closed) {
            return;
        }
        this.isStopped = true;
        _super.prototype.unsubscribe.call(this);
    };
    Subscriber.prototype._next = function (value) {
        this.destination.next(value);
    };
    Subscriber.prototype._error = function (err) {
        this.destination.error(err);
        this.unsubscribe();
    };
    Subscriber.prototype._complete = function () {
        this.destination.complete();
        this.unsubscribe();
    };
    Subscriber.prototype._unsubscribeAndRecycle = function () {
        var _parentOrParents = this._parentOrParents;
        this._parentOrParents = null;
        this.unsubscribe();
        this.closed = false;
        this.isStopped = false;
        this._parentOrParents = _parentOrParents;
        return this;
    };
    return Subscriber;
}(Subscription));
var SafeSubscriber = /*@__PURE__*/ (function (_super) {
    __extends(SafeSubscriber, _super);
    function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this._parentSubscriber = _parentSubscriber;
        var next;
        var context = _this;
        if (isFunction(observerOrNext)) {
            next = observerOrNext;
        }
        else if (observerOrNext) {
            next = observerOrNext.next;
            error = observerOrNext.error;
            complete = observerOrNext.complete;
            if (observerOrNext !== empty) {
                context = Object.create(observerOrNext);
                if (isFunction(context.unsubscribe)) {
                    _this.add(context.unsubscribe.bind(context));
                }
                context.unsubscribe = _this.unsubscribe.bind(_this);
            }
        }
        _this._context = context;
        _this._next = next;
        _this._error = error;
        _this._complete = complete;
        return _this;
    }
    SafeSubscriber.prototype.next = function (value) {
        if (!this.isStopped && this._next) {
            var _parentSubscriber = this._parentSubscriber;
            if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                this.__tryOrUnsub(this._next, value);
            }
            else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;
            if (this._error) {
                if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(this._error, err);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, this._error, err);
                    this.unsubscribe();
                }
            }
            else if (!_parentSubscriber.syncErrorThrowable) {
                this.unsubscribe();
                if (useDeprecatedSynchronousErrorHandling) {
                    throw err;
                }
                hostReportError(err);
            }
            else {
                if (useDeprecatedSynchronousErrorHandling) {
                    _parentSubscriber.syncErrorValue = err;
                    _parentSubscriber.syncErrorThrown = true;
                }
                else {
                    hostReportError(err);
                }
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.complete = function () {
        var _this = this;
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            if (this._complete) {
                var wrappedComplete = function () { return _this._complete.call(_this._context); };
                if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(wrappedComplete);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, wrappedComplete);
                    this.unsubscribe();
                }
            }
            else {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            this.unsubscribe();
            if (config.useDeprecatedSynchronousErrorHandling) {
                throw err;
            }
            else {
                hostReportError(err);
            }
        }
    };
    SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
        if (!config.useDeprecatedSynchronousErrorHandling) {
            throw new Error('bad call');
        }
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            if (config.useDeprecatedSynchronousErrorHandling) {
                parent.syncErrorValue = err;
                parent.syncErrorThrown = true;
                return true;
            }
            else {
                hostReportError(err);
                return true;
            }
        }
        return false;
    };
    SafeSubscriber.prototype._unsubscribe = function () {
        var _parentSubscriber = this._parentSubscriber;
        this._context = null;
        this._parentSubscriber = null;
        _parentSubscriber.unsubscribe();
    };
    return SafeSubscriber;
}(Subscriber));
//# sourceMappingURL=Subscriber.js.map

/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */
function canReportError(observer) {
    while (observer) {
        var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
        if (closed_1 || isStopped) {
            return false;
        }
        else if (destination && destination instanceof Subscriber) {
            observer = destination;
        }
        else {
            observer = null;
        }
    }
    return true;
}
//# sourceMappingURL=canReportError.js.map

/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */
function toSubscriber(nextOrObserver, error, complete) {
    if (nextOrObserver) {
        if (nextOrObserver instanceof Subscriber) {
            return nextOrObserver;
        }
        if (nextOrObserver[rxSubscriber]) {
            return nextOrObserver[rxSubscriber]();
        }
    }
    if (!nextOrObserver && !error && !complete) {
        return new Subscriber(empty);
    }
    return new Subscriber(nextOrObserver, error, complete);
}
//# sourceMappingURL=toSubscriber.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })();
//# sourceMappingURL=observable.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function noop() { }
//# sourceMappingURL=noop.js.map

/** PURE_IMPORTS_START _noop PURE_IMPORTS_END */
function pipeFromArray(fns) {
    if (!fns) {
        return noop;
    }
    if (fns.length === 1) {
        return fns[0];
    }
    return function piped(input) {
        return fns.reduce(function (prev, fn) { return fn(prev); }, input);
    };
}
//# sourceMappingURL=pipe.js.map

/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */
var Observable = /*@__PURE__*/ (function () {
    function Observable(subscribe) {
        this._isScalar = false;
        if (subscribe) {
            this._subscribe = subscribe;
        }
    }
    Observable.prototype.lift = function (operator) {
        var observable = new Observable();
        observable.source = this;
        observable.operator = operator;
        return observable;
    };
    Observable.prototype.subscribe = function (observerOrNext, error, complete) {
        var operator = this.operator;
        var sink = toSubscriber(observerOrNext, error, complete);
        if (operator) {
            sink.add(operator.call(sink, this.source));
        }
        else {
            sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
                this._subscribe(sink) :
                this._trySubscribe(sink));
        }
        if (config.useDeprecatedSynchronousErrorHandling) {
            if (sink.syncErrorThrowable) {
                sink.syncErrorThrowable = false;
                if (sink.syncErrorThrown) {
                    throw sink.syncErrorValue;
                }
            }
        }
        return sink;
    };
    Observable.prototype._trySubscribe = function (sink) {
        try {
            return this._subscribe(sink);
        }
        catch (err) {
            if (config.useDeprecatedSynchronousErrorHandling) {
                sink.syncErrorThrown = true;
                sink.syncErrorValue = err;
            }
            if (canReportError(sink)) {
                sink.error(err);
            }
            else {
                console.warn(err);
            }
        }
    };
    Observable.prototype.forEach = function (next, promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var subscription;
            subscription = _this.subscribe(function (value) {
                try {
                    next(value);
                }
                catch (err) {
                    reject(err);
                    if (subscription) {
                        subscription.unsubscribe();
                    }
                }
            }, reject, resolve);
        });
    };
    Observable.prototype._subscribe = function (subscriber) {
        var source = this.source;
        return source && source.subscribe(subscriber);
    };
    Observable.prototype[observable] = function () {
        return this;
    };
    Observable.prototype.pipe = function () {
        var operations = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            operations[_i] = arguments[_i];
        }
        if (operations.length === 0) {
            return this;
        }
        return pipeFromArray(operations)(this);
    };
    Observable.prototype.toPromise = function (promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var value;
            _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
        });
    };
    Observable.create = function (subscribe) {
        return new Observable(subscribe);
    };
    return Observable;
}());
function getPromiseCtor(promiseCtor) {
    if (!promiseCtor) {
        promiseCtor =  Promise;
    }
    if (!promiseCtor) {
        throw new Error('no Promise impl found');
    }
    return promiseCtor;
}
//# sourceMappingURL=Observable.js.map

function tnLineStdinReader() {
  return new Observable(subscribe => {
    const stdin = readline.createInterface(process.stdin);
    let tests = null;
    let n = null;
    stdin.on('line', line => {
      if (tests === null) {
        tests = +line;
      } else if (n === null) {
        n = +line;
        tests--;
      } else {
        n = null;
        subscribe.next(line);

        if (tests === 0) {
          stdin.close();
          subscribe.complete();
        }
      }
    });
  });
}

function isHappy(arr) {
  if (arr[0] <= 0 || arr[arr.length - 1] <= 0) {
    return 'NO';
  }

  let sum = 0;

  for (let x = 0; x < arr.length - 1; x++) {
    sum += arr[x];

    if (sum <= 0) {
      return 'NO';
    }
  }

  sum = 0;

  for (let x = arr.length - 1; x > 0; x--) {
    sum += arr[x];

    if (sum <= 0) {
      return 'NO';
    }
  }

  return 'YES';
}

tnLineStdinReader().subscribe(input => {
  const arr = input.split(' ').map(i => +i);
  console.log(isHappy(arr));
});


ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal —  and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?

The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0.

Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output  - 1 instead. If there are multiple solutions, you may print any of them.

NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square.

function solve(){
    var n;

var arr=[];

n = +readline();
for(var i=0;i<n;i++){
    arr[i]=readline().split(' ');
}

//print(arr[1][2]);
var x,y,j;
for(i=0;i<n;i++){
    for(j=0;j<n;j++){
        if(+arr[i][j]===0){
            x=i;
            y=j;
        }
    }
}

//print(''+x+' '+y);
var sum=0;
if(n==1){
    print(1);
    return;
}
if(x!==0){
    for(i = 0;i<n;i++){
        sum+= +arr[0][i];
    }
}else{
    for(i = 0;i<n;i++){
        sum+= +arr[1][i];
    }
}
//print(sum);
var cur=0;
for(i = 0;i<n;++i){
    cur+=+arr[x][i];
}
arr[x][y] = (sum-cur);
//print(arr[x][y]);
if(arr[x][y]<=0){
    print(-1);
    return;
}
cur=0;//diag
for(i=0;i<n;++i){
    cur+=+arr[i][i];
}
if(cur!=sum){
    print(-1);
    return;
}
cur=0;//2diag
for(i=0;i<n;++i){
    cur+=+arr[i][n-i-1];
}
if(cur!=sum){
    print(-1);
    return;
}
var cur1=0,cur2=0;
for(i=0;i<n;++i){
    cur1=0;
    cur2=0;
    for(j=0;j<n;++j){
        cur1+=+arr[i][j];
        cur2+=+arr[j][i];
    }
    if(cur1!==sum){
        print(-1);
        return;
    }
    if(cur2!==sum){
        print(-1);
        return;
    }
}

print(arr[x][y]);

}

solve();

var n = parseInt(readline());
var i0; var j0;
var matrix = [];

var supposedsum = 0;

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

    var j = 0;
    var row = readline().split(' ').map(function(x){
        var num = parseInt(x);

        if(num === 0) {
            i0 = i;
            j0 = j;
        }

        j++;
        return num;
    });

    matrix.push(row);
}

if(n === 1) {
    print(1);
} else {

    var sumrow0 = matrix[i0].reduce(function(prev, curr){
        return prev + curr;
    });

    // take any row for calculating guessed empty grid value
    var checkrow = i0 + 1;
    if(i0 === n - 1) { // check if empty grid on bottom edge
        checkrow = i0 - 1;
    }

    supposedsum = matrix[checkrow].reduce(function(prev, curr){
        return prev + curr;
    });

    //console.log("supposedsum: " + supposedsum);

    matrix[i0][j0] = supposedsum - sumrow0;

    //console.log("matrix[i0][j0]: " + matrix[i0][j0]);

    // start checking

    if(matrix[i0][j0] > 0)
    {
        var is_solution_exist = true;

        // check every row & column
        var sum_main_diagonal = 0;
        var sum_secondary_diagonal = 0;
        for(var i = 0; i < n; i++) {

            var sumrow = 0;
            var sumcol = 0;

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

                sumrow += matrix[i][j];
                sumcol += matrix[j][i];
            }

            sum_main_diagonal += matrix[i][i];
            sum_secondary_diagonal += matrix[i][n - i - 1];

            if(sumrow !== supposedsum || sumcol !== supposedsum) {
                is_solution_exist = false;
                break;
            }
        }

        if(is_solution_exist) {
            //console.log("check sum of every diagonal");
            //console.log("sum_main_diagonal: " + sum_main_diagonal);
            //console.log("sum_secondary_diagonal: " + sum_secondary_diagonal);
            // check if every diagonal
            is_solution_exist = sum_main_diagonal == supposedsum && sum_secondary_diagonal == supposedsum;
        }

        if(is_solution_exist)
            print(matrix[i0][j0]);
        else
            print(-1);
    }
    else
        print(-1);

}

/*
    The idea to solve this problem is basically straightforward:

    Assume matrix is magic square.

    Take any sum row / column, compare it with sum row / column containing zero, the result will be guessed empty grid value,
    after that test if new value is correct (must be positive integer and by checking sum of every row, every column, main diagonal, and secondary diagonal).

    If all tests passed then the matrix is magic square, otherwise it is not.
*/

var n = parseInt(readline());
var i0; var j0;
var matrix = [];

var supposedsum = 0;

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

    var j = 0;
    var row = readline().split(' ').map(function(x){
        var num = parseInt(x);

        if(num === 0) { // try to locate position of zero value
            i0 = i;
            j0 = j;
        }

        j++;
        return num;
    });

    matrix.push(row); // construct matrix
}

if(n === 1) {
    print(1); //  basically we can print any positive integer
} else {

    // get sum of row containing zero --> we can take sum row or sum col, btw
    var sumrow0 = matrix[i0].reduce(function(prev, curr){
        return prev + curr;
    });

    // take any row for calculating guessed empty grid value
    var checkrow = i0 + 1;
    if(i0 === n - 1) { // check if empty grid on bottom edge
        checkrow = i0 - 1;
    }

    // calculate supposed sum
    supposedsum = matrix[checkrow].reduce(function(prev, curr){
        return prev + curr;
    });

    // calculate guessed value
    matrix[i0][j0] = supposedsum - sumrow0;

    // start checking
    if(matrix[i0][j0] > 0) // check if guessed value is positive integer
    {
        var is_solution_exist = true;
        var sum_main_diagonal = 0;
        var sum_secondary_diagonal = 0;

        // check every row & column
        for(var i = 0; i < n; i++) {

            var sumrow = 0;
            var sumcol = 0;

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

                sumrow += matrix[i][j];
                sumcol += matrix[j][i];
            }

            sum_main_diagonal += matrix[i][i];
            sum_secondary_diagonal += matrix[i][n - i - 1];

            if(sumrow !== supposedsum || sumcol !== supposedsum) {
                is_solution_exist = false;
                break;
            }
        }

        if(is_solution_exist) {
            // check every diagonal value compared to supposedsum
            is_solution_exist = sum_main_diagonal == supposedsum && sum_secondary_diagonal == supposedsum;
        }

        if(is_solution_exist)
            print(matrix[i0][j0]);
        else
            print(-1);
    }
    else
        print(-1);

}

var n = parseInt(readline());
var i0; var j0;
var matrix = [];

var supposedsum = 0;

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

    var j = 0;
    var row = readline().split(' ').map(function(x){
        var num = parseInt(x);

        if(num === 0) {
            i0 = i;
            j0 = j;
        }

        j++;
        return num;
    });

    matrix.push(row);
}

if(n === 1) {
    print(1);
} else {

    var sumrow0 = matrix[i0].reduce(function(prev, curr){
        return prev + curr;
    });

    // take any row for calculating guessed empty grid value
    var checkrow = i0 + 1;
    if(i0 === n - 1) { // check if empty grid on bottom edge
        checkrow = i0 - 1;
    }

    supposedsum = matrix[checkrow].reduce(function(prev, curr){
        return prev + curr;
    });

    //console.log("supposedsum: " + supposedsum);

    matrix[i0][j0] = supposedsum - sumrow0;

    //console.log("matrix[i0][j0]: " + matrix[i0][j0]);

    // start checking
    var is_solution_exist = true;

    // check every row & column
    var sum_main_diagonal = 0;
    var sum_secondary_diagonal = 0;
    for(var i = 0; i < n; i++) {

        var sumrow = 0;
        var sumcol = 0;

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

            sumrow += matrix[i][j];
            sumcol += matrix[j][i];
        }

        sum_main_diagonal += matrix[i][i];
        sum_secondary_diagonal += matrix[i][n - i - 1];

        if(sumrow !== supposedsum || sumcol !== supposedsum) {
            is_solution_exist = false;
            break;
        }
    }

    if(is_solution_exist) {
        //console.log("check sum of every diagonal");
        //console.log("sum_main_diagonal: " + sum_main_diagonal);
        //console.log("sum_secondary_diagonal: " + sum_secondary_diagonal);
        // check if every diagonal
        is_solution_exist = sum_main_diagonal == supposedsum && sum_secondary_diagonal == supposedsum;
    }

    if(is_solution_exist)
        print(matrix[i0][j0]);
    else
        print(-1);

}


Another Codeforces Round has just finished! It has gathered $$$n$$$ participants, and according to the results, the expected rating change of participant $$$i$$$ is $$$a_i$$$. These rating changes are perfectly balanced — their sum is equal to $$$0$$$.Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.There are two conditions though:   For each participant $$$i$$$, their modified rating change $$$b_i$$$ must be integer, and as close to $$$\frac{a_i}{2}$$$ as possible. It means that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. In particular, if $$$a_i$$$ is even, $$$b_i = \frac{a_i}{2}$$$. Here $$$\lfloor x \rfloor$$$ denotes rounding down to the largest integer not greater than $$$x$$$, and $$$\lceil x \rceil$$$ denotes rounding up to the smallest integer not smaller than $$$x$$$.  The modified rating changes must be perfectly balanced — their sum must be equal to $$$0$$$. Can you help with that?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 13\,845$$$), denoting the number of participants. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$-336 \le a_i \le 1164$$$), denoting the rating change of the $$$i$$$-th participant. The sum of all $$$a_i$$$ is equal to $$$0$$$.

Output $$$n$$$ integers $$$b_i$$$, each denoting the modified rating change of the $$$i$$$-th participant in order of input. For any $$$i$$$, it must be true that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. The sum of all $$$b_i$$$ must be equal to $$$0$$$. If there are multiple solutions, print any. We can show that a solution exists for any valid input.

NoteIn the first example, $$$b_1 = 5$$$, $$$b_2 = -3$$$ and $$$b_3 = -2$$$ is another correct solution.In the second example there are $$$6$$$ possible solutions, one of them is shown in the example output.

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here
let input = "";
process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
	const numbers = input.split("\n").filter(x => x.trim() !== "").filter((_, i) => i !== 0).map(Number);
	let oddCount = (numbers.map(x => x % 2 !== 0).reduce((acc, cur) => acc + cur, 0)) / 2;
	for (let i = 0; i < numbers.length; i++) {
		if (numbers[i] % 2 === 0) {
			numbers[i] /= 2;
			continue;
        }
		if (numbers[i] % 2 !== 0) {
			if (oddCount > 0) {
                numbers[i]--;
                oddCount--;
            } else {
				numbers[i]++;
			}
			numbers[i] /= 2;
		}
	}
	console.log(numbers.join("\n"));
});

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')
  const n = parseInt(arr.shift())

  let nF = false, pF = false
  for(let i = 0; i < n; i++) {
    let num = parseInt(arr[i])
    if(num % 2 == 0) console.log(num / 2)
    else if(num == 0) {
      console.log(0)
    }

    else if(num > 0) {
      if(pF) {
        console.log((num + 1) / 2)
      }
      else {
        console.log((num - 1) / 2)
      }
      pF = !pF
    }

    else {
      if(pF) {
        console.log((num + 1) / 2)
      }
      else {
        console.log((num - 1) / 2)
      }
      pF = !pF
    }
  }
})

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

let countStr = 0;
const dataArr = [];

rl.on('line', (line) => {
  line = Number(line);
  if (!countStr) {
    countStr = line;
    return;
  }

  dataArr.push(line);
  if (dataArr.length === countStr) {
    start();
  }
});

function start() {
  let flag = true;
  for (let i of dataArr) {
    if (i % 2 === 0) {
      console.log(i / 2);
      continue;
    }

    let a;

    if (flag) {
      a = Math.floor(i / 2);
    } else {
      a = Math.ceil(i / 2);
    }

    if (a > -1 && a < 1) {
      a = 0;
    }
    console.log(a);

    flag = !flag;
  }

  rl.close();
}

var count = parseInt(readline());
// var arr = [10, -5, -5]
// var count = 3;
var balance = 0;

for (var i = 0; i < count; i++) {
  var curr = parseInt(readline());
  // var curr = arr[i]
  if (curr % 2 === 0) {
    write((curr / 2) + '\n');
  }
  else if (balance) {
    balance = 0;
    write(Math.floor(curr / 2) + '\n');
  } else {
    write(Math.ceil(curr / 2) + '\n');
    balance = 1;
  }
}

  var n = readline();

    var raing =[];
    var hadCorrection =[];
    var newRating =[];
    var sum = 0;

    for(var i=0;i<n;i++)
    {
        raing[i] = readline();
        if(raing[i]%2==0) newRating[i]=raing[i]/2;
        else
        {
            newRating[i] =Math.floor(raing[i]/2);
            hadCorrection[i]=1;
        }

        sum+=newRating[i];

    }

    for(var i=n-1;i>=0;i--)
    {
        var temp = newRating[i];
        if((sum>0 && hadCorrection[i]<0)
        || sum<0 && hadCorrection[i]>0)
        {
            newRating[i] = newRating[i]+hadCorrection[i];
            sum += newRating[i]-temp;
           // print("new rating = "+newRating[i]+" Sum : "+sum);
        }

    }

    for(var i=0;i<n;i++)print(newRating[i]);

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

var f1 = false;
for(var i=0; i<T; i++) {

        var ar = readline().split(' ').map(x => parseInt(x));

        if(ar % 2 === 0) {
                print(ar / 2);

        } else if(f1) {
                print(Math.floor(ar / 2));
                f1 = false;

        } else {
                print(Math.ceil(ar / 2));
                f1 = true;
        }
}

//

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here
let input = "";
process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
	console.log(input.split('\n').filter((_, i) => i !== 0).map(Number).map(x => x / 2).map(Math.round).join("\n"));
});

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')
  const n = parseInt(arr.shift())

  let nF = false, pF = false
  for(let i = 0; i < n; i++) {
    let num = parseInt(arr[i])
    if(num % 2 == 0) console.log(num / 2)
    else if(num == 0) {
      console.log(0)
    }

    else if(num > 0) {
      if(pF) {
        console.log(Math.floor(num / 2))
      }
      else {
        console.log(Math.ceil(num / 2))
      }
      pF = !pF
    }

    else {
      if(pF) {
        console.log(Math.floor(num / 2))
      }
      else {
        console.log(Math.ceil(num / 2))
      }
      pF = !pF
    }
  }
})

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

let countStr = 0;
const dataArr = [];

rl.on('line', (line) => {
  line = Number(line);
  if (!countStr) {
    countStr = line;
    return;
  }

  dataArr.push(line);
  if (dataArr.length === countStr) {
    start();
  }
});

function start() {
  let flag = true;
  for (let i of dataArr) {
    if (i % 2 === 0) {
      console.log(i / 2);
      continue;
    }

    if (flag) {
      console.log(Math.floor(i / 2));
    } else {
      console.log(Math.ceil(i / 2));
    }

    flag = !flag;
  }

  rl.close();
}

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

let countStr = 0;
const dataArr = [];

rl.on('line', (line) => {
  line = Number(line);
  if (!countStr) {
    countStr = line;
    return;
  }

  dataArr.push(line);
  if (dataArr.length === countStr) {
    start();
  }
});

function start() {
  let flag = false;
  for (let i of dataArr) {
    if (i % 2 === 0) {
      console.log(i / 2);
      continue;
    }

    if (flag) {
      console.log(Math.floor(i / 2));
    } else {
      console.log(Math.ceil(i / 2));
    }

    flag = !flag;
  }

  rl.close();
}


You and your $$$n - 1$$$ friends have found an array of integers $$$a_1, a_2, \dots, a_n$$$. You have decided to share it in the following way: All $$$n$$$ of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the $$$m$$$-th position in the line. Before the process starts, you may choose up to $$$k$$$ different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer $$$x$$$ such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to $$$x$$$?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains three space-separated integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le m \le n \le 3500$$$, $$$0 \le k \le n - 1$$$)  — the number of elements in the array, your position in line and the number of people whose choices you can fix. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3500$$$.

For each test case, print the largest integer $$$x$$$ such that you can guarantee to obtain at least $$$x$$$.

NoteIn the first test case, an optimal strategy is to force the first person to take the last element and the second person to take the first element.  the first person will take the last element ($$$5$$$) because he or she was forced by you to take the last element. After this turn the remaining array will be $$$[2, 9, 2, 3, 8]$$$;  the second person will take the first element ($$$2$$$) because he or she was forced by you to take the first element. After this turn the remaining array will be $$$[9, 2, 3, 8]$$$;  if the third person will choose to take the first element ($$$9$$$), at your turn the remaining array will be $$$[2, 3, 8]$$$ and you will take $$$8$$$ (the last element);  if the third person will choose to take the last element ($$$8$$$), at your turn the remaining array will be $$$[9, 2, 3]$$$ and you will take $$$9$$$ (the first element). Thus, this strategy guarantees to end up with at least $$$8$$$. We can prove that there is no strategy that guarantees to end up with at least $$$9$$$. Hence, the answer is $$$8$$$.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with $$$4$$$.

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var nmk = readline()
      .split(" ")
      .map(Number);

    var n = nmk[0];
    var m = nmk[1];
    var k = nmk[2];

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

    if (k >= m) {
      k = m - 1;
    }

    var currMax;
    var max = 0;
    var leftInd = 0;
    var rightInd = arr.length - 1;
    for (var j = 0; j <= k; j++) {
      leftInd = j;
      rightInd = n - (k - j);
      // минимальный из максимумов при выбранных к
      currMax = findCurrMin(arr, leftInd, rightInd, m - k - 1);
      if (currMax > max) {
        max = currMax;
      }
    }

    print(max);
  }
}

function findCurrMin(arr, left, right, wr) {
  var leftC, rightC;
  var maxH;
  var minMax = 1000000000;
  for (var a = 0; a <= wr; a++) {
    leftC = left + a;
    rightC = right - (wr - a);
    if (arr[leftC] > arr[rightC - 1]) {
      maxH = arr[leftC];
    } else {
      maxH = arr[rightC - 1];
    }
    if (maxH < minMax) {
      minMax = maxH;
    }
  }
  return minMax;
}
main()

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var nmk = readline()
      .split(" ")
      .map(Number);

    var n = nmk[0];
    var m = nmk[1];
    var k = nmk[2];

    var max = 0;
    var arr = readline()
      .split(" ")
      .map(Number);

    if (k >= m) {
      k = m - 1;
    }

    var leftInd = 0;
    var rightInd = arr.length - 1;
    for (var j = 0; j < k; j++) {
      var newInds = getMin(arr, leftInd, rightInd);
      leftInd = newInds.left;
      rightInd = newInds.right;
    }

    for (var a = 0; a < m - k - 1; a++) {
      var newInds = getMax(arr, leftInd, rightInd);
      leftInd = newInds.left;
      rightInd = newInds.right;
    }

    if (arr[leftInd] > arr[rightInd]) {
      max = arr[leftInd];
    } else {
      max = arr[rightInd];
    }
    print(max);
  }
}

function getMin(arr, left, right) {
  if (arr[left] < arr[right]) {
    left++;
  } else {
    right--;
  }
  return {
    left: left,
    right: right
  };
}

function getMax(arr, left, right) {
  if (arr[left] > arr[right]) {
    left++;
  } else {
    right--;
  }
  return {
    left: left,
    right: right
  };
}
main()


Vlad came home and found out that someone had reconfigured the old thermostat to the temperature of $$$a$$$.The thermostat can only be set to a temperature from $$$l$$$ to $$$r$$$ inclusive, the temperature cannot change by less than $$$x$$$. Formally, in one operation you can reconfigure the thermostat from temperature $$$a$$$ to temperature $$$b$$$ if $$$|a - b| \ge x$$$ and $$$l \le b \le r$$$.You are given $$$l$$$, $$$r$$$, $$$x$$$, $$$a$$$ and $$$b$$$. Find the minimum number of operations required to get temperature $$$b$$$ from temperature $$$a$$$, or say that it is impossible.

The first line of input data contains the single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each case contains three integers $$$l$$$, $$$r$$$ and $$$x$$$ ($$$-10^9 \le l \le r \le 10^9$$$, $$$1 \le x \le 10^9$$$) — range of temperature and minimum temperature change. The second line of each case contains two integers $$$a$$$ and $$$b$$$ ($$$l \le a, b \le r$$$) — the initial and final temperatures.

Output $$$t$$$ numbers, each of which is the answer to the corresponding test case. If it is impossible to achieve the temperature $$$b$$$, output -1, otherwise output the minimum number of operations.

NoteIn the first example, the thermostat is already set up correctly.In the second example, you can achieve the desired temperature as follows: $$$4 \rightarrow 10 \rightarrow 5$$$.In the third example, you can achieve the desired temperature as follows: $$$3 \rightarrow 8 \rightarrow 2 \rightarrow 7$$$.In the fourth test, it is impossible to make any operation.

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [l, r, x] = rns(),
        [a, b] = rns();
  if (a === b) return 0;
  if (Math.abs(a - b) >= x) return 1;
  if (a - l < x && r - a < x) return -1;
  if (b - l < x && r - b < x) return -1;
  if (a - l >= x) {
    if (b - l >= x) return 2;
  }
  if (r - a >= x) {
    if (r - b >= x) return 2;
  }
  return 3;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

'use strict';

function solve([l, r, x], [a, b]) {
    if (a === b) {
        return 0
    }

    if (Math.abs(l - r) < x) {
        return -1;
    }

    if (Math.abs(a - b) >= x) {
        return 1;
    }

    if (a > b) {
        var tmp = a;
        a = b;
        b = tmp;
    }

    if (r - b >= x || a - l >= x) {
        return 2;
    }

    if (r - a >= x && b - l >= x) {
        return 3;
    }

    return -1;
}

function main() {
    const numOfCases = rlsn();

    for (let testCase = 0; testCase < numOfCases; testCase++) {
        const l1 = rlarrn();
        const l2 = rlarrn();

        const res = solve(l1, l2);
        cl(res);
    }
}

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

let inStr = '';
let curLine = 0;
const cl = console.log;

process.stdin.on('data', function(inStdin) {inStr += inStdin;});
process.stdin.on('end', function() {inStr = inStr.split('\n');main();});

function readline() {return inStr[curLine++].replace(/\s+$/g, '');}
function rlsn() {return Number(readline());}
function rlarrstr() {return readline().split(' ');}
function rlarrn() {return rlarrstr().map(Number);}
function makeFreqMap(str) {const m={};for (let char of str) m[char]=m[char]+1||1;return m;}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [left, right, x] = lines[l++].trim().split(' ').map(Number)
        const [a, b] = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(left, right, x, a, b)
    }
    console.log(output.join('\n'))
// })()
})

function solve(l, r, x, a, b) {
    if (a === b) return 0
    if (b >= a + x || b <= a - x) return 1
    if (b < a) {
        if (a + x <= r || b - x >= l) return 2
        if (a - x >= l && b + x <= r) return 3
        return -1
    } else {
        if (a - x >= l || b + x <= r) return 2
        if (a + x <= r && b - x >= l) return 3
        return -1
    }
}

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var firstLine = readline().split(' ').map(Number);
    var l = firstLine[0];
    var r = firstLine[1];
    var x = firstLine[2];

    var secondLine = readline().split(' ').map(Number);
    var a = secondLine[0];
    var b = secondLine[1];

    var result = process(l, r, x, a, b);
    print(result);
}

function process(l, r, x, a, b) {
    if (a === b) {
        return 0
    }

    if (Math.abs(l - r) < x) {
        return -1;
    }

    if (Math.abs(a - b) >= x) {
        return 1;
    }

    if (a > b) {
        var tmp = a;
        a = b;
        b = tmp;
    }

    if (r - b >= x || a - l >= x) {
        return 2;
    }

    if (r - a >= x && b - l >= x) {
        return 3;
    }

    return -1;
}

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [l, r, x] = rns(),
        [a, b] = rns();
  if (a === b) return 0;
  if (Math.abs(a - b) >= x) return 1;
  if (a - l < x && r - a < x) return -1;
  if (b - l < x && r - b < x) return -1;
  if (a - l > x) {
    if (b - l > x) return 2;
  }
  if (r - a > x) {
    if (r - b > x) return 2;
  }
  return 3;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();


When you play the game of thrones, you win, or you die. There is no middle ground.Cersei Lannister, A Game of Thrones by George R. R. MartinThere are $$$n$$$ nobles, numbered from $$$1$$$ to $$$n$$$. Noble $$$i$$$ has a power of $$$i$$$. There are also $$$m$$$ "friendships". A friendship between nobles $$$a$$$ and $$$b$$$ is always mutual.A noble is defined to be vulnerable if both of the following conditions are satisfied:   the noble has at least one friend, and  all of that noble's friends have a higher power. You will have to process the following three types of queries.   Add a friendship between nobles $$$u$$$ and $$$v$$$.  Remove a friendship between nobles $$$u$$$ and $$$v$$$.  Calculate the answer to the following process. The process: all vulnerable nobles are simultaneously killed, and all their friendships end. Then, it is possible that new nobles become vulnerable. The process repeats itself until no nobles are vulnerable. It can be proven that the process will end in finite time. After the process is complete, you need to calculate the number of remaining nobles.Note that the results of the process are not carried over between queries, that is, every process starts with all nobles being alive!

The first line contains the integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2\cdot 10^5$$$, $$$0 \le m \le 2\cdot 10^5$$$) — the number of nobles and number of original friendships respectively. The next $$$m$$$ lines each contain the integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$), describing a friendship. No friendship is listed twice. The next line contains the integer $$$q$$$ ($$$1 \le q \le 2\cdot {10}^{5}$$$) — the number of queries.  The next $$$q$$$ lines contain the queries themselves, each query has one of the following three formats.    $$$1$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — add a friendship between $$$u$$$ and $$$v$$$. It is guaranteed that $$$u$$$ and $$$v$$$ are not friends at this moment.  $$$2$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — remove a friendship between $$$u$$$ and $$$v$$$. It is guaranteed that $$$u$$$ and $$$v$$$ are friends at this moment.  $$$3$$$ — print the answer to the process described in the statement.

For each type $$$3$$$ query print one integer to a new line. It is guaranteed that there will be at least one type $$$3$$$ query.

NoteConsider the first example. In the first type 3 query, we have the diagram below.In the first round of the process, noble $$$1$$$ is weaker than all of his friends ($$$2$$$ and $$$3$$$), and is thus killed. No other noble is vulnerable in round 1. In round 2, noble $$$3$$$ is weaker than his only friend, noble $$$4$$$, and is therefore killed. At this point, the process ends, and the answer is $$$2$$$.  In the second type 3 query, the only surviving noble is $$$4$$$.    The second example consists of only one type $$$3$$$ query. In the first round, two nobles are killed, and in the second round, one noble is killed. The final answer is $$$1$$$, since only one noble survives.

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

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

function main () {
	const [n, m] = rna();

	const deg = Array(n+1).fill(0);
	for (let i = 0; i < m; i++) {
		const [u, v] = rna();
		++deg[Math.min(u, v)];
	}

	let ans = 0;
	for (let u = 1; u <= n; u++) {
		ans += deg[u] == 0
	}

	let q = rn();
	while (q--) {
		const [op, u, v] = rna();

		if (op == 1) {
			if (++deg[Math.min(u, v)] == 1) ans--;
		} else if (op == 2) {
			if (--deg[Math.min(u, v)] == 0) ans++;
		} else {
			console.log(ans);
		}
	}
}

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

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

function main () {
	const [n, m] = rna();
	const adj = Array.from(Array(n+1), x => []);
	const cnt = Array(n+1).fill(0);
	for (let i = 0; i < m; i++) {
		let [u, v] = rna();
		adj[u].push(v);
		adj[v].push(u);
		++cnt[Math.min(u, v)];
	}

	let ans = 0;
	for (let u = 1; u <= n; u++) {
		ans += cnt[u] == 0
	}

	let q = rn();
	while (q--) {
		let [type, u, v] = rna();

		if (type == 1) {
			if (++cnt[Math.min(u, v)] == 1) {
				ans--;
			}
		} else if (type == 2) {
			if (--cnt[Math.min(u, v)] == 0) {
				ans++;
			}
		} else {
			console.log(ans);
		}
	}
}

function splitInput(i) {
    return i.split('\n')
}

function splitLine(l) {
    return l.split(' ').map((e) => +e)
}

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

let input = ''

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

process.stdin.on('end', () => {
    const lines = splitInput(input.trim())
    run(lines.map((l) => splitLine(l)))
})

function output(o) {
    process.stdout.write(`${o}\n`)
}

function run(lines) {
    let iterator = 0
    let [n, m] = lines[iterator++]
    const inDegrees = Array(n + 1).fill(0)
    inDegrees[0] = null
    let nodesWithInDegreeZero = n

    while (m > 0) {
        --m
        const [nodeA, nodeB] = lines[iterator++]
        const minNode = Math.min(nodeA, nodeB)
        if (inDegrees[minNode] === 0) {
            --nodesWithInDegreeZero
        }
        ++inDegrees[minNode]
    }

    let [q] = lines[iterator++]
    while (q > 0) {
        --q
        const [type, nodeA, nodeB] = lines[iterator++]
        switch (type) {
            case 1: {
                const minNode = Math.min(nodeA, nodeB)
                if (inDegrees[minNode] === 0) {
                    --nodesWithInDegreeZero
                }
                ++inDegrees[minNode]
            }
                break
            case 2: {
                const minNode = Math.min(nodeA, nodeB)
                if (inDegrees[minNode] === 1) {
                    ++nodesWithInDegreeZero
                }
                --inDegrees[minNode]
            }
                break
            case 3: {
                output(nodesWithInDegreeZero)
            }
        }
    }
}

const main = () => {

	var n, m;
	var _in = readIntArr();
	n = _in[0];
	m = _in[1];
	var maxCnts = n;
	var largerCnts = [];
	for (var i = 0; i < n + 1; i++) {
		largerCnts.push(0);
	}
	for (var _ = 0; _ < m; _++) {
		_in = readIntArr();
		var u = _in[0];
		var v = _in[1];
		if (u > v) {
			var temp = v;
			v = u;
			u = temp;
		}
		if (++largerCnts[u] === 1) {
			maxCnts--;
		}
	}

	var q = readInt();
	var allans = [];
	for (var _ = 0; _ < q; _++) {
		_in = readIntArr();
		if (_in.length === 1) { // 3
			allans.push(maxCnts);
			continue;
		}
		var x, u, v;
		x = _in[0];
		u = _in[1];
		v = _in[2];
		if (u > v) {
			var temp = v;
			v = u;
			u = temp;
		}
		if (x === 2) {
			if (--largerCnts[u] === 0) {
				maxCnts++;
			}
		} else { // x === 1
			if (++largerCnts[u] === 1) {
				maxCnts--;
			}
		}
	}
	multiLineArrayPrint(allans);

	return;
}

const readInt = () => parseInt(readline());
const readString = () => readline();
const readIntArr = () => readline().split(" ").map(zzzz => parseInt(zzzz));
const parseLong = (string) => { // javascript's largest long is < (1<<62)
	var n = string.length;
	var res = 0;
	for (var i = 0; i < n; i++) {
		res *= 10;
		res += parseInt(string[i]);
	}
	return res;
}
const readLong = () => parseLong(readLong());
const readLongArr = () => readline().split(" ").map(zzzz => parseLong(zzzz));
const oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));
const multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\n'));
const multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\n'));
const makeArr = (defaultVal, dimensionsArr) => {
	var n = dimensionsArr.length;
	if (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);
	else {
		var temp = [];
		for (var i = 0; i < dimensionsArr[0]; i++)
			temp.push(makeArr(defaultVal, dimensionsArr.slice(1)));
		return temp;
	}
}

for (_ = 0; _ < 1; _++) {
	main();
}

// newline for testing
 //newline for testing
// codeforces js cannot use "let" keyword. use "var" instead
// codeforces js cannot destructure arrays

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function printline(s, end = "\n") {
  process.stdout.write(s + end);
}

let alive = 0;
const under = [];
const upper = [];

function main() {
  const [n, m] = readline().split(' ').map((rl) => parseInt(rl, 10));;

  for (let i = 0; i <= n; ++i) {
    upper.push(0);
    under.push(0);
  }
  alive = n;

  for (let i = 1; i <= m; ++i) {
    const [u, v] = readline().split(' ').map((rl) => parseInt(rl, 10));
    if (upper[Math.min(u, v)] === 0) alive--;
    upper[Math.min(u, v)]++;
    under[Math.max(u, v)]++;
  }

  let q = parseInt(readline(), 10);
  while (q--) {
    const query = readline().split(' ').map((rl) => parseInt(rl, 10));
    if (query.length === 1) {
      printline(alive);
    } else {
      const u = query[1];
      const v = query[2];
      if (query[0] === 1) {
        if (upper[Math.min(u, v)] === 0) alive--;
        upper[Math.min(u, v)]++;
        under[Math.max(u, v)]++;
      } else {
        upper[Math.min(u, v)]--;
        if (upper[Math.min(u, v)] === 0) alive++;
        under[Math.max(u, v)]--;
      }
    }

  }

}

// run: cat input.txt | node C.js

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
  const [n, m] = readline().split(' ').map(x => parseInt(x));
  const deg = [];
  for(let i = 0; i < n; i++) {
    deg.push(0)
  }
  for(let i = 0; i < m; i++) {
    const [u, v] = readline().split(' ').map(x => parseInt(x));
    deg[Math.min(u-1, v-1)]++;
  }
  let ans = 0
  for(let i = 0; i < n; i++) {
    if(deg[i] === 0) {
      ans++;
    }
  }
  const show = (deg) => console.log(...deg)
  const q = parseInt(readline())
  for(let i = 0; i < q; i++) {
    const query = readline().split(' ').map(x => parseInt(x));
    if(query[0] === 3) {
      console.log(ans)
    } else {
      const who = Math.min(query[1]-1, query[2]-1)
      if(query[0] === 1) {
        deg[who]++;
        if(deg[who] === 1) {
          ans--
        }
      } else {
        deg[who]--;
        if(deg[who] === 0) {
          ans++
        }
      }
    }
  }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

var maxN = 2 * 1e5 + 10
var mod = 1e9 + 7

function main() {
  // Array(Number(xx)).fill(1).map((t, i) => {
  var [n, m] = readline().split(' ').map((x, iii) => {
    return parseInt(x)
  })
  var a = new Array(n)
  // for (let i = 0; i <; i++) {
  //
  // }
  var alive = new Array(n).fill(true)
  var willDie = new Array(n).fill(false)
  var count = new Array(n).fill(0)
  for (let i = 0; i < m; i++) {
    var [u, v] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    if (u > v) {
      var swap = u
      u = v
      v = swap
    }

    u--
    v--
    willDie[Math.min(u, v)] = true
    count[u]++
  }
  var res = 0
  for (let i = 0; i < n; i++) {
    if (!willDie[i]) res++
  }
  var q = parseInt(readline());

  for (let i = 0; i < q; i++) {
    var [req, u, v] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    u--
    v--

    if (u > v) {
      var swap = u
      u = v
      v = swap
    }
    if (req === 3) {
      console.log(res)
    }
    if (req === 2) {
      count[u]--
      if (count[u] === 0) res++
    }
    if (req === 1) {
      count[u]++
      if (count[u] === 1) res--
    }
  }
  // })
  // var res = new Array(n)
}

function plus(a, b, res) {
// console.log(a, b, res)
  if (a === 0) return res

  return plus(a < 0 ? a + 1 : a - 1, b, a < 0 ? res - b : res + b)
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function printline(s, end = "\n") {
  process.stdout.write(s + end);
}

let alive = 0;
const under = [];
const upper = [];

function main() {
  const [n, m] = readline().split(' ').map((rl) => parseInt(rl, 10));;

  for (let i = 0; i <= n; ++i) {
    upper.push(0);
    under.push(0);
  }
  alive = n;

  for (let i = 1; i <= m; ++i) {
    const [u, v] = readline().split(' ').map((rl) => parseInt(rl, 10));
    if (upper[Math.min(u, v)] === 0) alive--;
    upper[Math.min(u, v)]++;
    under[Math.max(u, v)]++;
  }

  let q = parseInt(readline(), 10);
  while (q--) {
    const query = readline().split(' ').map((rl) => parseInt(rl, 10));
    if (query.length === 1) {
      printline(alive);
    } else {
      const u = query[1];
      const v = query[2];
      if (query[0] === 1) {
        if (upper[Math.min(u, v)] === 0) alive--;
        upper[Math.min(u, v)]++;
        under[Math.max(u, v)]++;
      } else {
        upper[Math.min(u, v)]--;
        if (upper[Math.min(u, v)] === 0) alive--;
        under[Math.max(u, v)]--;
      }
    }

  }

}

// run: cat input.txt | node C.js


Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2 × 2 which are the Cheaterius' magic amulets!    That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2 × 2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk.

The first line contains an integer n (1 ≤ n ≤ 1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located.

var n = parseInt(readline());
var dominos = [];

var getMin = function(v) {
	var arr = [
		parseInt(v[0] + v[1] + v[2] + v[3]),
		parseInt(v[1] + v[2] + v[3] + v[0]),
		parseInt(v[2] + v[3] + v[0] + v[1]),
		parseInt(v[3] + v[0] + v[1] + v[2])
	];
	return arr.sort(s)[0];
};

var s = function(a, b) {
	return a - b;
};

for(var i = 0; i < n; i++) {
	var inp1 = readline();
	var inp2 = readline();
	var val = inp1 + inp2[1] + inp2[0];
	var minVal = getMin(val);
	dominos.push(minVal);
	if (i < n-1) {
		readline();
	}
}

dominos.sort(s);
var curr = dominos[0];
var num = 1;

for (var j = 1; j < n; j++) {
	if (dominos[j] != curr) {
		curr = dominos[j];
		num++;
	}
}

print(num);


Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".Not all students are equally sociable. About each student you know the value ai — the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that:  the student i sends no more than ai messages (for all i from 1 to n);  all students knew the news about the credit (initially only Polycarp knew it);  the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.

The first line contains the positive integer n (2 ≤ n ≤ 100) — the number of students.  The second line contains the sequence a1, a2, ..., an (0 ≤ ai ≤ 100), where ai equals to the maximum number of messages which can the i-th student agree to send. Consider that Polycarp always has the number 1.

Print -1 to the first line if it is impossible to inform all students about credit.  Otherwise, in the first line print the integer k — the number of messages which will be sent. In each of the next k lines print two distinct integers f and t, meaning that the student number f sent the message with news to the student number t. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can receive repeated messages with news of the credit.  If there are several answers, it is acceptable to print any of them.

NoteIn the first test Polycarp (the student number 1) can send the message to the student number 2, who after that can send the message to students number 3 and 4. Thus, all students knew about the credit.

readline();

var tmp_i = 1;
var maxes = readline().split(' ').map(function(x){

    return [tmp_i++, parseInt(x)];
});
var queue = [maxes.shift()];
var log = [];

maxes.sort(function(a, b){

    return b[1] - a[1];
});

while (queue.length > 0) {

    var std = queue[0][0];
    var cap = queue[0][1];

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

        if(maxes.length > 0) {
            log.push([std, maxes[0][0]]);
            queue.push(maxes.shift());
        }
        else
            break;
    }

    queue.shift();
}

if(maxes.length === 0) {

    print(log.length);
    for(var i = 0; i < log.length; i++)
        print(log[i].join(' '));
} else
    print(-1);

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;
  nums = nums.slice(1).map(function (x, i) {
    canSend += +x;
    return [+x, i+2, 0];
  });

  if ((+canSend + +procof) < +(col-1)) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  print(numbers.length -1);
  numbers.slice(1).forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;
if (!peoples[0].available && peoples.length > 1) print(-1);
else calculate(peoples);

function getUnknownIndex(peoplesArr) {
  var max = 0;
  var ind = -1;

  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow && peoplesArr[i].available >=max) {
      max = peoplesArr[i].available;
      ind = i;
    }
  }
  return ind;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0 && peoplesArr[i].isKnow) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return true;
    }
  }
  return false;
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    if (!say(result, peoplesArr, unknownIndex)) {
      print(-1);
      return;
    }
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

/*
readline()
print
*/

var iamdone = false;
var strings = [];
var n = +((readline() + "").trim());
var a = (readline() + "").trim().split(" ");
a = a.map((v, i) => {
    return {
        i: i + 1,
        v: +v,
        c: false
    }
}).sort(function(a, b){
    if(a.v > b.v) return -1; else return 1;
    return 0;
});

for(var i = 0; i < n; i++){
    if(a[i].i === 1){
        if(a[i].v === 0){
            iamdone = true;
        }else{
            a[i].v--;
            a[i].c = true;
        }
        break;
    }
}

if(iamdone){
    print("-1");
}else{
    if(a[0].i == 1){
        a[1].c = true;
        strings[strings.length] = "1 " + a[1].i;
    }else{
        a[0].c = true;
        strings[strings.length] = "1 " + a[0].i;
    }

    var link1 = 0;
    var link2 = 0;

    while(true){
        if(a[link1].v > 0 && a[link2].c === false){
            a[link1].v--;
            a[link2].c = true;
            strings[strings.length] = a[link1].i + " " + a[link2].i;
            link2++;
        }else if(a[link1].v <= 0){
            link1++;
        }else if(a[link2].c === true){
            link2++;
        }

        if(!a[link1] || !a[link2]){
            break;
        }
    }

    var error = false;

    for(var i = 0; i < n; i++){
        if(a[i].c === false){
            error = true;
            break;
        }
    }

    if(error){
        print("-1");
    }else{
        print(strings.length);
        for(var i = 0; i < strings.length; i++){
            print(strings[i]);
        }
    }

}

function getNearestNotNofiedStudent(students) {
    for (var i = 0; i < students.length; i++) {
        if (students[i].notified === false) {
            return students[i];
        }
    }

    return null;
}

function run(students) {
    // print('hello!');

    students = students.map(function (student) {
        student.notified = false;
        return student;
    });

    var polikarp = students[0];

    polikarp.notified = true;

    if (polikarp.limit === 0) {
        // print('polikarp');
        return -1;
    }

    var overallLimit = students.reduce(function (acc, student) {
       return acc + student.limit;
    }, 0);

    if (students.length > overallLimit + 1) {
        // print('students');
        return -1;
    }

    students = students.sort(function (left, right) {
        if (left.notified) {
            return -1;
        }

        if (right.notified) {
            return 1;
        }

        if (left.limit === right.limit) {
            return 0;
        }

        return left.limit < right.limit ? 1 : -1;
    });

    var messages = [];

    for (var i = 0; i < students.length; i++) {
        var currentStudent = students[i];
        while (currentStudent.limit > 0) {
            var notNotifiedStudent = getNearestNotNofiedStudent(students);
            if (notNotifiedStudent === null) {
                break;
            }
            notNotifiedStudent.notified = true;
            currentStudent.limit--;
            messages.push({
                from: currentStudent.number,
                to: notNotifiedStudent.number
            });
        }
    }

    return (
        messages.length + "\n" +
        messages.reduce(function (acc, message) {
            return acc + message.from + ' ' + message.to + "\n";
        }, '')
    );
}

var count = readline();
var students = readline()
    .split(' ')
    .map(function (a) { return parseInt(a); })
    .map(function (limit, number) {
        return { limit: limit, number: number + 1 };
    });

var result = run(students);
print(result);

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;
  nums = nums.slice(1).map(function (x, i) {
    canSend += +x;
    return [+x, i+2, 0];
  });

  if (+canSend < +col-1) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  numbers = numbers.slice(1).sort((a, b) => a[2] - b[2]);
  print(numbers.length);
  numbers.forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;
  nums = nums.slice(1).map(function (x, i) {
    canSend += +x;
    return [+x, i+2, 0];
  });

  if (+canSend < +col-1) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  print(numbers.length);
  numbers.slice(1).forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;
  nums = nums.slice(1).map(function (x, i) {
    canSend += +x;
    return [+x, i+2, 0];
  });
  if (+canSend < +col) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  numbers = numbers.slice(1).sort((a, b) => a[2] - b[2]);
  print(numbers.length);
  numbers.forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;

  nums = nums.slice(1).map(function (x, i) {
    canSend += x;
    return [+x, i+2, 0];
  });
  if (canSend < col) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  numbers = numbers.slice(1).sort((a, b) => a[2] - b[2]);
  print(numbers.length);
  numbers.forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;

if (!peoples[0].available) print(-1);
else calculate(peoples);

function getUnknownIndex(peoplesArr) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow) return i;
  }
  return -1;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return;
    }
  }
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    say(result, peoplesArr, unknownIndex);
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;
if (!peoples[0].available) print(-1);
else calculate(peoples);

function getUnknownIndex(peoplesArr) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow) return i;
  }
  return -1;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return true;
    }
  }
  return false;
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    if (!say(result, peoplesArr, unknownIndex)) {
      print(-1);
      return;
    }
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;

calculate(peoples);

function getUnknownIndex(peoplesArr) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow) return i;
  }
  return -1;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return;
    }
  }
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    say(result, peoplesArr, unknownIndex);
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;
if (!peoples[0].available) print(-1);
else calculate(peoples);

function getUnknownIndex(peoplesArr) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow) return i;
  }
  return -1;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0 && peoplesArr[i].isKnow) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return true;
    }
  }
  return false;
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    if (!say(result, peoplesArr, unknownIndex)) {
      print(-1);
      return;
    }
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

/*
readline()
print
*/

var iamdone = false;
var strings = [];
var n = +((readline() + "").trim());
var a = (readline() + "").trim().split(" ");
a = a.map((v, i) => {
    return {
        i: i + 1,
        v: v,
        c: false
    }
}).sort(function(a, b){
    if(a.v > b.v) return -1; else return 1;
    return 0;
});

for(var i = 0; i < n; i++){
    if(a[i].i === 1){
        if(a[i].v === 0){
            iamdone = true;
        }else{
            a[i].v--;
            a[i].c = true;
        }
    }
}

if(iamdone){
    print("-1");
}else{
    if(a[0].i == 1){
        a[1].c = true;
        strings[strings.length] = "1 " + a[1].i;
    }else{
        a[0].c = true;
        strings[strings.length] = "1 " + a[0].i;
    }

    var link1 = 0;
    var link2 = 0;

    while(true){
        if(a[link1].v > 0 && a[link2].c === false){
            a[link1].v--;
            a[link2].c = true;
            strings[strings.length] = a[link1].i + " " + a[link2].i;
            link2++;
        }else if(a[link1].v <= 0){
            link1++;
        }else if(a[link2].c === true){
            link2++;
        }

        if(!a[link1] || !a[link2]){
            break;
        }
    }

    var error = false;

    for(var i = 0; i < n; i++){
        if(a[i].c === false){
            error = true;
            break;
        }
    }

    if(error){
        print("-1");
    }else{
        print(strings.length);
        for(var i = 0; i < strings.length; i++){
            print(strings[i]);
        }
    }

}

/*
readline()
print
*/

var iamdone = false;
var strings = [];
var n = +((readline() + "").trim());
var a = (readline() + "").trim().split(" ").map((v, i) => {
    var c = false;
    if(i === 0){
        v--;
        c = true;
        if(v < 0) iamdone = true;
    }
    return {
        i: i + 1,
        v: v,
        c: c
    }
}).sort(function(a, b){
    if(a.v > b.v) return -1; else return 1;
    return 0;
});

if(iamdone){
    print("-1");
}else{
    a[0].c = true;
    strings[strings.length] = "1 " + a[0].i;

    var link1 = 0;
    var link2 = 0;

    while(true){
        if(a[link1].v > 0 && a[link2].c === false){
            a[link1].v--;
            a[link2].c = true;
            strings[strings.length] = a[link1].i + " " + a[link2].i;
            link2++;
        }else if(a[link1].v <= 0){
            link1++;
        }else if(a[link2].c === true){
            link2++;
        }

        if(!a[link1] || !a[link2]){
            break;
        }
    }

    var error = false;

    for(var i = 0; i < n; i++){
        if(a[i].c === false){
            error = true;
            break;
        }
    }

    if(error){
        print("-1");
    }else{
        print(strings.length);
        for(var i = 0; i < strings.length; i++){
            print(strings[i]);
        }
    }

}

function getNearestNotNofiedStudent(students) {
    for (var i = 0; i < students.length; i++) {
        if (students[i].notified === false) {
            return students[i];
        }
    }

    return null;
}

function run(students) {
    // print('hello!');

    students = students.map(function (student) {
        student.notified = false;
        return student;
    });

    var polikarp = students[0];

    polikarp.notified = true;

    if (polikarp.limit === 0) {
        // print('polikarp');
        return -1;
    }

    var overallLimit = students.reduce(function (acc, student) {
       return acc + student.limit;
    }, 0);

    if (students.length > overallLimit + 1) {
        // print('students');
        return -1;
    }

    students = students.sort(function (left, right) {
        if (left.notified) {
            return -1;
        }

        if (right.notified) {
            return 1;
        }

        if (left.limit === right.limit) {
            return 0;
        }

        return left.limit < right.limit ? 1 : -1;
    });

    var messages = [];

    for (var i = 0; i < students.length; i++) {
        var currentStudent = students[i];
        while (currentStudent.limit > 0) {
            var notNotifiedStudent = getNearestNotNofiedStudent(students);
            if (notNotifiedStudent === null) {
                break;
            }
            notNotifiedStudent.notified = true;
            currentStudent.limit--;
            messages.push({
                from: currentStudent.number,
                to: notNotifiedStudent.number
            });
        }
    }

    return messages.reduce(function (acc, message) {
        return acc + message.from + ' ' + message.to + "\n";
    }, '');
}

var count = readline();
var students = readline()
    .split(' ')
    .map(function (a) { return parseInt(a); })
    .map(function (limit, number) {
        return { limit: limit, number: number + 1 };
    });

var result = run(students);
print(result);