This problem is an extension of the problem "Wonderful Coloring - 1". It has quite many differences, so you should read this statement completely.Recently, Paul and Mary have found a new favorite sequence of integers $$$a_1, a_2, \dots, a_n$$$. They want to paint it using pieces of chalk of $$$k$$$ colors. The coloring of a sequence is called wonderful if the following conditions are met:  each element of the sequence is either painted in one of $$$k$$$ colors or isn't painted;  each two elements which are painted in the same color are different (i. e. there's no two equal values painted in the same color);  let's calculate for each of $$$k$$$ colors the number of elements painted in the color — all calculated numbers must be equal;  the total number of painted elements of the sequence is the maximum among all colorings of the sequence which meet the first three conditions. E. g. consider a sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. One of the wonderful colorings of the sequence is shown in the figure.    The example of a wonderful coloring of the sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. Note that one of the elements isn't painted. Help Paul and Mary to find a wonderful coloring of a given sequence $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first one contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le n$$$) — the length of a given sequence and the number of colors, respectively. The second one contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, each of them must contain a description of a wonderful coloring for the corresponding test case. Each wonderful coloring must be printed as a sequence of $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$0 \le c_i \le k$$$) separated by spaces where   $$$c_i=0$$$, if $$$i$$$-th element isn't painted;  $$$c_i>0$$$, if $$$i$$$-th element is painted in the $$$c_i$$$-th color.  Remember that you need to maximize the total count of painted elements for the wonderful coloring. If there are multiple solutions, print any one.

NoteIn the first test case, the answer is shown in the figure in the statement. The red color has number $$$1$$$, the blue color — $$$2$$$, the green — $$$3$$$.

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        var [n, k] = lines[l++].trim().split(' ').map(Number)
        var arr = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k, arr))
    }
});

function solve(n, k, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const ch = arr[i]
        map[ch] = (map[ch] || 0) + 1
    }

    let a = 0
    let b = 0
    const start = {}
    for (let x in map) {
        const count = map[x]
        if (count >= k) {
            a++
        } else {
            start[x] = b
            b += count
        }
    }
    const max = Math.floor(b / k) * k
// console.log(a, 'max', max)
// console.log(start)
    // let idx = 0
    const cur = {}
    return arr.map(x => {
        const count = map[x]
        let color = 0
        if (count >= k) {
            cur[x] = cur[x] || 1
            if (cur[x] <= k) {
                color = cur[x]++
            }
        } else {
            // if (idx < max) {
            const now = start[x] + (cur[x] || 0)
            // console.log(now, max)
            if (now < max) {
                color = now + 1
                if (color % k) color = color % k
                else color = k
                // console.log(now, color)

                cur[x] = (cur[x] || 0) + 1
            }
        }
        return color
    }).join(' ')
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL);

  // iter lines
  const cases = lines[0] - 0;

  for (let i = 1; i <= cases; i++) {
    const [n,k] = lines[2*i - 1].split(' ').map(x => parseInt(x));
    const arr = lines[2*i].split(' ').map(x => parseInt(x));
    // console.log(n,k,arr);
    // create a map for cycle
    const map = {};
    // pos[num] = [each pos]
    const pos = {};
    const rpos = {};
    const cnts = {};
    const ans = [];
    let target_count = 0;
    // count how many times each num appears, iter j
    for (let j = 0; j < arr.length; j++) {

      if (map[arr[j]]) {
        map[arr[j]]++;
      } else {
        map[arr[j]] = 1;
      }

      // pos
      if (pos[arr[j]]) {
        pos[arr[j]].push(j);
        // add target_count if arr[j] appeared less than k times
        if (map[arr[j]] <= k) {
          target_count++;
        }

      } else {
        pos[arr[j]] = [j];
        cnts[arr[j]] = 0;
        target_count+=1;
      }
    }

    // left target_count number should be multiple of k
    target_count -= (target_count % k);

    const poses = [];
    // flatten pos to poses
    for (let key in pos) {
      poses.push(...pos[key]);
    }

    // console.log(pos, poses, cnts)
    // console.log(target_count, map);

    // iter thru poses
    let color = 1;
    for (let j = 0; j < poses.length; j++) {
      // get now pos
      const now = poses[j];
      // get cnts of this num
      const cnt = cnts[arr[now]];
      // put ans cnt+1 if cnt < k
      if (cnt < k && target_count > 0) {
        ans[now] = color++;
        cnts[arr[now]]++;
        if(color > k) {
          color = 1;
        }
        target_count--;
      } else {
        ans[now] = 0;
      }

    }

    console.log(ans.join(' '));

  }

})

'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
let n;
let k;
let a;
let nxt;
let last;
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        k = nextInt();
        a = af(n);
        nxt = af(n).fill(INIT);
        last = af(n + 1).fill(INIT);
        const ans = af(n).fill(0);
        const uniq = new Set();
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
            uniq.add(a[i]);
            if (last[a[i]] != INIT) {
                nxt[i] = last[a[i]];
            }
            last[a[i]] = i;
        }
        let p = [];
        let i = 0;
        for (let v of uniq.values()) {
            for (let j = 0; j < k && last[v] != INIT; j++) {
                p.push(last[v]);
                last[v] = nxt[last[v]];
            }
        }
        let l = p.length - (p.length % k);
        check((l % k) == 0);
        for (let i = 0; i < l; i++) {
            ans[p[i]] = (i % k) + 1;
        }
        printf("%s\n", ans.join(' '));
        // printf("%j\n", nxt);
        // cnt.forEach((v: number, k: number) => { printf("%d=%d\n", v, k) });
        // console.log(cnt);
    }
}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const assert = (condition) => { if (!condition) throw new Error("Assertion failed"); }
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const int = parseInt;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg2 = Math.log2;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };
const initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
const ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);
const isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };
const initializeGraph = (n) => { let G = []; for (let i = 0; i < n; i++) { G.push([]); } return G; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 09/05/21 night
const solve = (n, k, A) => {
    let a = initializeGraph(n + 1);
    for (let i = 0; i < n; i++) a[A[i]].push(i);
    // pr(a);
    let res = Array(n).fill(0);
    let b = [];
    for (let i = 1; i <= n; i++) {
        if (a[i].length < k) {
            for (const x of a[i]) b.push(x);
            continue;
        }
        for (let j = 0; j < k; j++) {
            res[a[i][j]] = j + 1;
        }
    }
    // pr(res)
    // pr(b)
    for (let i = 0; i + k <= b.length; i += k) {
        for (let j = 0; j < k; j++) {
            res[b[i + j]] = j + 1;
        }
    }
    pr(res.join(" "))
};

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

main()

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

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

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();
		const a = rna();

		const mp = new Map();
		for (let i = 0; i < n; i++) {
			if (mp.has(a[i]))
				mp.get(a[i]).push(i);
			else
				mp.set(a[i], [i]);
		}

		const avl = [];
		for (const [elm, indxs] of mp) {
			for (let i = 0 ; i < indxs.length && i < k; i++) {
				avl.push(indxs[i]);
			}
		}

		const ans = Array(n).fill(0);
		for (let i = 0, clr = 0; i < Math.floor(avl.length/k)*k; i++) {
			clr = clr%k + 1;
			ans[avl[i]] = clr;
		}

		console.log(ans.join(' '));
	}
}

const readNum = () => +readline();
const readStr = () => readline();
const readNumArr = () => readline().split(' ').map(item => +item);

const n = readNum();

for(var i = 0; i < n; i++) {
  var ans = readNumArr();
  var m = ans[0];
  var k = ans[1];
  var vals = readNumArr();

  ans = []

  var uniq = new Map();
  var count = 0;

  for(var j = 0; j < m; j++) {
    var item = uniq.get(vals[j]);
    ans[j] = 0;

    if(!item) {
      uniq.set(vals[j], []);
      item = uniq.get(vals[j]);
    }

    item.push(j)
  }

  uniq.forEach(item => {
    count += item.length < k ? item.length : k;
  });

  count -= count % k;

  var lk = 0;

  uniq.forEach(item => {
    for(var j = 0; j < item.length && j < k; j++) {
      if(count) {
        lk++;
        ans[item[j]] = lk;
        if(lk === k) {
          lk = 0;
        }
        count--;
      }
    }
  });

  print(ans.join(' '));
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        var [n, k] = lines[l++].trim().split(' ').map(Number)
        var arr = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k, arr))
    }
});

function solve(n, k, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const ch = arr[i]
        map[ch] = (map[ch] || 0) + 1
    }

    let a = 0
    let b = 0
    const start = {}
    for (let x in map) {
        const count = map[x]
        if (count >= k) {
            a++
        } else {
            start[x] = b
            b += count
        }
    }
    const max = Math.floor(b / k) * k
// console.log(a, 'max', max)
    let idx = 0
    const cur = {}
    return arr.map(x => {
        const count = map[x]
        let color = 0
        if (count >= k) {
            cur[x] = cur[x] || 1
            if (cur[x] <= k) {
                color = cur[x]++
            }
        } else {
            // if (idx < max) {
            if (idx < max && start[x] < max) {
                cur[x] = cur[x] || 1
                color = (start[x] + cur[x]++) % k
                color++
                // color = (idx++ % k) + 1
                idx++
            }
        }
        return color
    }).join(' ')
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        var [n, k] = lines[l++].trim().split(' ').map(Number)
        var arr = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k, arr))
    }
});

function solve(n, k, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const ch = arr[i]
        map[ch] = (map[ch] || 0) + 1
    }

    let a = 0
    let b = 0
    const start = {}
    for (let x in map) {
        const count = map[x]
        if (count >= k) {
            a++
        } else {
            start[x] = b
            b += count
        }
    }
    const max = Math.floor(b / k) * k
// console.log(a, 'max', max)
    let idx = 0
    const cur = {}
    return arr.map(x => {
        const count = map[x]
        let color = 0
        if (count >= k) {
            cur[x] = cur[x] || 1
            if (cur[x] <= k) {
                color = cur[x]++
            }
        } else {
            if (idx < max) {
                cur[x] = cur[x] || 1
                color = (start[x] + cur[x]++) % k
                color++
                // color = (idx++ % k) + 1
                idx++
            }
        }
        return color
    }).join(' ')
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        var [n, k] = lines[l++].trim().split(' ').map(Number)
        var arr = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k, arr))
    }
});

function solve(n, k, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const ch = arr[i]
        map[ch] = (map[ch] || 0) + 1
    }

    const p = []
    for (let x in map) {
        const count = map[x]
        p.push(count)
    }
    p.sort((a, b) => a - b)

    const pre = []
    p.forEach((x, i) => {
        pre[i] = i ? pre[i - 1] + x : x
    })
// console.log(p, pre)
    let max = -Infinity
    let ek
    let limit
    for (let i = 1; i <= k; i++) {
        const idx = binarySearch(0, p.length - 1, x => p[x] < i)
        const b = idx < 0 ? 0 : pre[idx]
        const a = p.length - 1 - idx
        const cur = (a + Math.floor(b / i)) * i
        // console.log(i, a, b, cur)
        if (cur > max) {
            max = cur
            ek = i
            limit = Math.floor(b / i) * i
        }
    }
    // console.log(max, ek, limit)
    k = ek
// console.log(a, 'max', max)
    let idx = 0
    const cur = {}
    return arr.map(x => {
        const count = map[x]
        let color = 0
        if (count >= k) {
            cur[x] = cur[x] || 1
            if (cur[x] <= k) {
                color = cur[x]++
            }
        } else {
            if (idx < limit) {
                color = (idx++ % k) + 1
            }
        }
        return color
    }).join(' ')
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        var [n, k] = lines[l++].trim().split(' ').map(Number)
        var arr = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k, arr))
    }
});

function solve(n, k, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const ch = arr[i]
        map[ch] = (map[ch] || 0) + 1
    }

    let a = 0
    let b = 0
    for (let x in map) {
        const count = map[x]
        if (count >= k) {
            a++
        } else {
            b += count
        }
    }
    const max = Math.floor(b / k) * k
// console.log(a, 'max', max)
    let idx = 0
    const cur = {}
    return arr.map(x => {
        const count = map[x]
        let color = 0
        if (count >= k) {
            cur[x] = cur[x] || 1
            if (cur[x] <= k) {
                color = cur[x]++
            }
        } else {
            if (idx < max) {
                color = (idx++ % k) + 1
            }
        }
        return color
    }).join(' ')
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        var [n, k] = lines[l++].trim().split(' ').map(Number)
        var arr = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k, arr))
    }
});

function solve(n, k, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const ch = arr[i]
        map[ch] = (map[ch] || 0) + 1
    }

    let idx = 0
    const cur = {}
    return arr.map(x => {
        const count = map[x]
        let color = 0
        if (count >= k) {
            cur[x] = cur[x] || 1
            if (cur[x] <= k) {
                color = cur[x]++
            }
        } else {
            color = idx + 1
            idx = (idx + 1) % k
        }
        return color
    }).join(' ')
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL);

  // iter lines
  const cases = lines[0] - 0;

  for (let i = 1; i <= cases; i++) {
    const [n,k] = lines[2*i - 1].split(' ').map(x => parseInt(x));
    const arr = lines[2*i].split(' ').map(x => parseInt(x));
    // console.log(n,k,arr);
    // create a map for cycle
    const map = {};
    // pos[num] = [each pos]
    const pos = {};
    const rpos = {};
    const cnts = {};
    const ans = [];
    let target_count = 0;
    // count how many times each num appears, iter j
    for (let j = 0; j < arr.length; j++) {

      if (map[arr[j]]) {
        map[arr[j]]++;
      } else {
        map[arr[j]] = 1;
      }

      // pos
      if (pos[arr[j]]) {
        pos[arr[j]].push(j);
        // add target_count if arr[j] appeared less than k times
        if (map[arr[j]] <= k) {
          target_count++;
        }

      } else {
        pos[arr[j]] = [j];
        cnts[arr[j]] = 0;
        target_count+=1;
      }
    }

    // left target_count number should be multiple of k
    target_count -= (target_count % k);

    const poses = [];
    // flatten pos to poses
    for (let key in pos) {
      poses.push(...pos[key]);
    }

    // console.log(pos, poses, cnts)
    // console.log(target_count, map);

    // iter thru poses
    let color = 1;
    // for (let j = 0; j < poses.length; j++) {
    //   // get now pos
    //   const now = poses[j];
    //   // get cnts of this num
    //   const cnt = cnts[arr[now]];
    //   // put ans cnt+1 if cnt < k
    //   if (cnt < k && target_count > 0) {
    //     ans[now] = color++;
    //     cnts[arr[now]]++;
    //     if(color > k) {
    //       color = 1;
    //     }
    //     target_count--;
    //   } else {
    //     ans[now] = 0;
    //   }

    // }

    // iter through arr
    for (let j = 0; j < arr.length; j++) {
      // get cnts of this num
      const cnt = cnts[arr[j]];
      // put ans color if cnt < k
      if (cnt < k && target_count > 0) {
        ans[j] = color++;
        cnts[arr[j]]++;
        if(color > k) {
          color = 1;
        }
        target_count--;
      } else {
        ans[j] = 0;
      }
    }

    console.log(ans.join(' '));

  }

})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL);

  // iter lines
  const cases = lines[0] - 0;

  for (let i = 1; i <= cases; i++) {
    const [n,k] = lines[2*i - 1].split(' ').map(x => parseInt(x));
    const arr = lines[2*i].split(' ').map(x => parseInt(x));
    // console.log(n,k,arr);
    // create a map for cycle
    const map = {};
    // pos[num] = [each pos]
    const pos = {};
    const rpos = {};
    const cnts = {};
    const ans = [];
    // count how many times each num appears, iter j
    for (let j = 0; j < arr.length; j++) {

      if (map[arr[j]]) {
        map[arr[j]]++;
      } else {
        map[arr[j]] = 1;
      }

      // pos
      if (pos[arr[j]]) {
        pos[arr[j]].push(j);
      } else {
        pos[arr[j]] = [j];
        cnts[arr[j]] = 0;
      }
    }

    const poses = [];
    // flatten pos to poses
    for (let key in pos) {
      poses.push(...pos[key]);
    }

    // console.log(pos, poses, cnts)

    // iter thru poses
    let color = 1;
    for (let j = 0; j < poses.length; j++) {
      // get now pos
      const now = poses[j];
      // get cnts of this num
      const cnt = cnts[arr[now]];
      // put ans cnt+1 if cnt < k
      if (cnt < k) {
        ans[now] = color++;
        cnts[arr[now]]++;
        if(color > k) {
          color = 1;
        }
      } else {
        ans[now] = 0;
      }

    }

    console.log(ans.join(' '));

  }

})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL);

  // iter lines
  const cases = lines[0] - 0;

  for (let i = 1; i <= cases; i++) {
    const [n,k] = lines[2*i - 1].split(' ').map(x => parseInt(x));
    const arr = lines[2*i].split(' ').map(x => parseInt(x));
    // console.log(n,k,arr);
    // create a map for cycle
    const map = new Map();
    const ans = [];
    // count how many times each num appears
    for (let j = 0; j < arr.length; j++) {
      const num = arr[j] - 0;
      if (map.has(num)) {
        map.set(num, map.get(num) + 1);
      } else {
        map.set(num, 1);
      }
    }

    // iter through the map values, init keys to zero
    const used = {};
    for (let key of map.keys()) {
      used[key] = 0;
    }

    // start from color 1, cycle through ~k
    let color = 1;
    // iter throught nums
    for (let j = 0; j < arr.length; j++) {
      const num = arr[j] - 0;
      // if num is already used k times, skip it
      if (used[num] >= k) {
        // put 0 to ans
        ans.push(0);
        continue;
      }
      // count used
      used[num] = used[num] + 1;
      // put color to ans
      ans.push(color);
      // color++
      color++;
      // if color > k, reset color to 1
      if (color > k) {
        color = 1;
      }

    }

    console.log(ans);

  }

})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL);

  // iter lines
  const cases = lines[0] - 0;

  for (let i = 1; i <= cases; i++) {
    const [n,k] = lines[2*i - 1].split(' ').map(x => parseInt(x));
    const arr = lines[2*i].split(' ').map(x => parseInt(x));
    // console.log(n,k,arr);
    // create a map for cycle
    const map = new Map();
    const ans = [];
    // for each num in arr
    for (let j = 0; j < arr.length; j++) {
      // if the num is not in map, add it
      if (!map.has(arr[j])) {
        map.set(arr[j], 1);
      }
      // else if the num is in map, increase the count by 1
      else {
        map.set(arr[j], map.get(arr[j]) + 1);
        // if the count is more than k, put 0 to ans
        if (map.get(arr[j]) > k) {
          ans.push(0);
          continue;
        }
      }
      // put the map num to ans
      ans.push(map.get(arr[j]));

    }

    console.log(ans.join(' '));

  }

})

'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
let n;
let k;
let a;
let nxt;
let last;
let cnt;
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        k = nextInt();
        a = af(n);
        nxt = af(n).fill(INIT);
        last = af(n + 1).fill(INIT);
        cnt = af(n + 1).fill(0);
        const ans = af(n).fill(0);
        const uniq = new Set();
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
            uniq.add(a[i]);
            cnt[a[i]]++;
            if (last[a[i]] != INIT) {
                nxt[i] = last[a[i]];
            }
            last[a[i]] = i;
        }
        let p = af(n);
        let i = 0;
        for (let v of uniq.values()) {
            for (let j = 0; j < k && last[v] != INIT; j++) {
                p[i++] = last[v];
                last[v] = nxt[last[v]];
            }
        }
        let l = p.length - (p.length % k);
        for (let i = 0; i < l; i++) {
            ans[p[i]] = (i % k) + 1;
        }
        printf("%s\n", ans.join(' '));
        // printf("%j\n", nxt);
        // cnt.forEach((v: number, k: number) => { printf("%d=%d\n", v, k) });
        // console.log(cnt);
    }
}

'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
let n;
let k;
let a;
let ans;
let nxt;
let last;
let cnt;
let uniq;
function answer(len) {
    const can = new Set(uniq.values());
    const rem = Array.from(cnt);
    const p = Array.from(last);
    ans.fill(0);
    for (let col = 1; col <= k; col++) {
        if (can.size < len) {
            return false;
        }
        let g = 0;
        for (let v of can.values()) {
            check(p[v] != INIT);
            check(rem[v] > 0);
            ans[p[v]] = col;
            p[v] = nxt[p[v]];
            rem[v]--;
            if (rem[v] == 0) {
                can.delete(v);
            }
            g++;
            if (g >= len) {
                break;
            }
        }
    }
    //  printf("answer %d ok\n", len);
    return true;
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        k = nextInt();
        a = af(n);
        nxt = af(n).fill(INIT);
        last = af(n + 1).fill(INIT);
        cnt = af(n + 1).fill(0);
        ans = af(n).fill(0);
        uniq = new Set();
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
            uniq.add(a[i]);
            cnt[a[i]]++;
            if (last[a[i]] != INIT) {
                nxt[i] = last[a[i]];
            }
            last[a[i]] = i;
        }
        let lo = 0;
        let hi = n;
        let best = INIT;
        while (lo < hi) {
            let mid = lo + Math.trunc((hi - lo) / 2);
            // printf("mid %d\n", mid);
            if (answer(mid)) {
                best = mid;
                lo = mid + 1;
            }
            else {
                hi = mid;
            }
        }
        check(best != INIT);
        answer(best);
        printf("%s\n", ans.join(' '));
        // printf("%j\n", nxt);
        // cnt.forEach((v: number, k: number) => { printf("%d=%d\n", v, k) });
        // console.log(cnt);
    }
}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const assert = (condition) => { if (!condition) throw new Error("Assertion failed"); }
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const int = parseInt;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg2 = Math.log2;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };
const initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
const ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);
const isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 07/23/21 morning
 * https://codeforces.com/contest/1551/problem/B2
 */
const solve = (n, k, a) => {
    // pr(n, k, a)
    let m = counter_value_in_indexA_in(a);
    let res = Array(n).fill(0);
    // pr(m)
    let red = 0;
    for (const [c, a] of m) {
        let occ = a.length;
        if (occ >= k) {
            red++;
            for (let i = 0, color = 1; i < k; i++, color++) {
                res[a[i]] = color;
            }
            m.delete(c);
        }
    }
    m = new Map([...m].sort((x, y) => y[1].length - x[1].length));
    // pr(m)
    // pr(res);
    let sum = 0;
    for (const [, a] of m) {
        sum += a.length;
    }
    let each = int(sum / k);
    let d = [];
    for (const [, aa] of m) {
       for(const i of aa) d.push(i);
    }
    // pr(res);
    for (let i = 0, color = 1; i < k; i++, color++) {
        if (d[i] < n) res[d[i]] = color;
    }
    pr(res)
    // let ca = Array.from(m.keys());
    // let n = ca.length;
    // let idx = 0;
    // for (; idx < n; ) {
    //     if (each == 0) break;
    //     let c = ca[idx];
    //     let a = m.get(c);
    //     let occ = a.length;
    //     if (occ >= k) {
    //         for (let i = 0, color = 1; i < k; i++, color++) {
    //             res[a[i]] = color;
    //             each--;
    //         }
    //         m.delete(c);
    //         idx++;
    //     } else {
    //         let rest = k - occ;
    //         for (let i = 0, color = 1; i < occ; i++, color++) {
    //             res[a[i]] = color;
    //             each--;
    //         }
    //         m.delete(c);
    //         idx++;
    //     }
    // }
};

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

main()


Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's".The restaurant "Alice's" serves $$$n$$$ kinds of food. The cost for the $$$i$$$-th kind is always $$$c_i$$$. Initially, the restaurant has enough ingredients for serving exactly $$$a_i$$$ dishes of the $$$i$$$-th kind. In the New Year's Eve, $$$m$$$ customers will visit Alice's one after another and the $$$j$$$-th customer will order $$$d_j$$$ dishes of the $$$t_j$$$-th kind of food. The $$$(i + 1)$$$-st customer will only come after the $$$i$$$-th customer is completely served.Suppose there are $$$r_i$$$ dishes of the $$$i$$$-th kind remaining (initially $$$r_i = a_i$$$). When a customer orders $$$1$$$ dish of the $$$i$$$-th kind, the following principles will be processed. If $$$r_i > 0$$$, the customer will be served exactly $$$1$$$ dish of the $$$i$$$-th kind. The cost for the dish is $$$c_i$$$. Meanwhile, $$$r_i$$$ will be reduced by $$$1$$$. Otherwise, the customer will be served $$$1$$$ dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $$$1$$$. If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $$$0$$$.If the customer doesn't leave after the $$$d_j$$$ dishes are served, the cost for the customer will be the sum of the cost for these $$$d_j$$$ dishes.Please determine the total cost for each of the $$$m$$$ customers.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), representing the number of different kinds of food and the number of customers, respectively. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$), where $$$a_i$$$ denotes the initial remain of the $$$i$$$-th kind of dishes. The third line contains $$$n$$$ positive integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 10^6$$$), where $$$c_i$$$ denotes the cost of one dish of the $$$i$$$-th kind. The following $$$m$$$ lines describe the orders of the $$$m$$$ customers respectively. The $$$j$$$-th line contains two positive integers $$$t_j$$$ and $$$d_j$$$ ($$$1 \leq t_j \leq n$$$, $$$1 \leq d_j \leq 10^7$$$), representing the kind of food and the number of dishes the $$$j$$$-th customer orders, respectively.

Print $$$m$$$ lines. In the $$$j$$$-th line print the cost for the $$$j$$$-th customer.

NoteIn the first sample, $$$5$$$ customers will be served as follows. Customer $$$1$$$ will be served $$$6$$$ dishes of the $$$2$$$-nd kind, $$$1$$$ dish of the $$$4$$$-th kind, and $$$1$$$ dish of the $$$6$$$-th kind. The cost is $$$6 \cdot 3 + 1 \cdot 2 + 1 \cdot 2 = 22$$$. The remain of the $$$8$$$ kinds of food will be $$$\{8, 0, 2, 0, 4, 4, 7, 5\}$$$. Customer $$$2$$$ will be served $$$4$$$ dishes of the $$$1$$$-st kind. The cost is $$$4 \cdot 6 = 24$$$. The remain will be $$$\{4, 0, 2, 0, 4, 4, 7, 5\}$$$. Customer $$$3$$$ will be served $$$4$$$ dishes of the $$$6$$$-th kind, $$$3$$$ dishes of the $$$8$$$-th kind. The cost is $$$4 \cdot 2 + 3 \cdot 2 = 14$$$. The remain will be $$$\{4, 0, 2, 0, 4, 0, 7, 2\}$$$. Customer $$$4$$$ will be served $$$2$$$ dishes of the $$$3$$$-rd kind, $$$2$$$ dishes of the $$$8$$$-th kind. The cost is $$$2 \cdot 3 + 2 \cdot 2 = 10$$$. The remain will be $$$\{4, 0, 0, 0, 4, 0, 7, 0\}$$$. Customer $$$5$$$ will be served $$$7$$$ dishes of the $$$7$$$-th kind, $$$3$$$ dishes of the $$$1$$$-st kind. The cost is $$$7 \cdot 3 + 3 \cdot 6 = 39$$$. The remain will be $$$\{1, 0, 0, 0, 4, 0, 0, 0\}$$$.In the second sample, each customer is served what they order except the last one, who leaves angrily without paying. For example, the second customer is served $$$6$$$ dishes of the second kind, so the cost is $$$66 \cdot 6 = 396$$$.In the third sample, some customers may not be served what they order. For example, the second customer is served $$$6$$$ dishes of the second kind, $$$6$$$ of the third and $$$1$$$ of the fourth, so the cost is $$$66 \cdot 6 + 666 \cdot 6 + 6666 \cdot 1 = 11058$$$.

"use strict";
function main(input) {
  const inputs = input.split("\n").filter(x => x !== "");

  const [n, m] = inputs[0].split(" ").map(Number);
  const a = inputs[1].split(" ").map(Number);
  const c = inputs[2].split(" ").map(Number);
  const t = [];
  const d = [];

  for (let i=0; i<m; i++) {
    let line = inputs[3 + i].split(" ").map(Number);
    t[i] = line[0];
    d[i] = line[1];
  }

  let sortedC = c.map((value, index) =>({ value, index})).sort((a,b) => a.value - b.value);
  let currentMinIndexInSortedC = 0;
  let currentMinIndex = sortedC[currentMinIndexInSortedC].index;
  let full = false;
  for (let i=0; i<m; i++) {
    let curT = t[i] - 1;
    let curD = d[i];
    let cost = 0;

    if (full) {
      console.log(0);
      continue;
    }

    if ( curD <= a[curT] ) {
      a[curT] = a[curT] - curD;
      cost += curD * c[curT];
      curD = 0;
    } else {
      curD = curD - a[curT];
      cost += a[curT] * c[curT];
      a[curT] = 0;

      while ( curD > 0 ) {
        if (curD < a[currentMinIndex]) {
          a[currentMinIndex] = a[currentMinIndex] - curD;
          cost += curD * c[currentMinIndex];
          curD = 0;
        } else {
          curD = curD - a[currentMinIndex];
          cost += a[currentMinIndex] * c[currentMinIndex];
          a[currentMinIndex] = 0;

          currentMinIndexInSortedC+=1;
          if (currentMinIndexInSortedC >= n) {
            if (curD > 0) {
              cost = 0;
              curD = 0;
            }
            full = true;
          } else {
            currentMinIndex = sortedC[currentMinIndexInSortedC].index;
          }
        }
      }
    }

    console.log(cost);
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  main(i)
})

"use strict";
function main(input) {
  const inputs = input.split("\n").filter(x => x !== "");

  const [n, m] = inputs[0].split(" ").map(Number);
  const a = inputs[1].split(" ").map(Number);
  const c = inputs[2].split(" ").map(Number);
  const t = [];
  const d = [];

  for (let i=0; i<m; i++) {
    let line = inputs[3 + i].split(" ").map(Number);
    t[i] = line[0];
    d[i] = line[1];
  }

  let sortedC = c.map((value, index) =>({ value, index})).sort((a,b) => a.value - b.value);
  let currentMinIndexInSortedC = 0;
  let currentMinIndex = sortedC[currentMinIndexInSortedC].index;
  let full = false;
  for (let i=0; i<m; i++) {
    let curT = t[i] - 1;
    let curD = d[i];
    let cost = 0;

    if (full) {
      console.log(0);
      continue;
    }

    if ( curD <= a[curT] ) {
      a[curT] = a[curT] - curD;
      cost += curD * c[curT];
      curD = 0;
    } else {
      curD = curD - a[curT];
      cost += a[curT] * c[curT];
      a[curT] = 0;

      while ( curD > 0 ) {
        if (curD < a[currentMinIndex]) {
          a[currentMinIndex] = a[currentMinIndex] - curD;
          cost += curD * c[currentMinIndex];
          curD = 0;
        } else {
          curD = curD - a[currentMinIndex];
          cost += a[currentMinIndex] * c[currentMinIndex];
          a[currentMinIndex] = 0;

          currentMinIndexInSortedC+=1;
          if (currentMinIndexInSortedC >= n) {
            if (curD > 0) {
              cost = 0;
              curD = 0;
            }
            full = true;
          } else {
            currentMinIndex = sortedC[currentMinIndexInSortedC].index;
          }
        }
      }
    }

    console.log(cost - 1);
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  main(i)
})


Завтра у хоккейной команды, которой руководит Евгений, важный матч. Евгению нужно выбрать шесть игроков, которые выйдут на лед в стартовом составе: один вратарь, два защитника и три нападающих.Так как это стартовый состав, Евгения больше волнует, насколько красива будет команда на льду, чем способности игроков. А именно, Евгений хочет выбрать такой стартовый состав, чтобы номера любых двух игроков из стартового состава отличались не более, чем в два раза. Например, игроки с номерами 13, 14, 10, 18, 15 и 20 устроят Евгения, а если, например, на лед выйдут игроки с номерами 8 и 17, то это не устроит Евгения.Про каждого из игроков вам известно, на какой позиции он играет (вратарь, защитник или нападающий), а также его номер. В хоккее номера игроков не обязательно идут подряд. Посчитайте число различных стартовых составов из одного вратаря, двух защитников и трех нападающих, которые может выбрать Евгений, чтобы выполнялось его условие красоты.

Первая строка содержит три целых числа g, d и f (1 ≤ g ≤ 1 000, 1 ≤ d ≤ 1 000, 1 ≤ f ≤ 1 000) — число вратарей, защитников и нападающих в команде Евгения.  Вторая строка содержит g целых чисел, каждое в пределах от 1 до 100 000 — номера вратарей. Третья строка содержит d целых чисел, каждое в пределах от 1 до 100 000 — номера защитников. Четвертая строка содержит f целых чисел, каждое в пределах от 1 до 100 000 — номера нападающих. Гарантируется, что общее количество игроков не превосходит 1 000, т. е. g + d + f ≤ 1 000. Все g + d + f номеров игроков различны.

Выведите одно целое число — количество возможных стартовых составов.

ПримечаниеВ первом примере всего один вариант для выбора состава, который удовлетворяет описанным условиям, поэтому ответ 1.Во втором примере подходят следующие игровые сочетания (в порядке вратарь-защитник-защитник-нападающий-нападающий-нападающий):  16 20 12 13 21 11  16 20 12 13 11 10  16 20 19 13 21 11  16 20 19 13 11 10  16 12 19 13 21 11  16 12 19 13 11 10 Таким образом, ответ на этот пример — 6.

var notNeeded = readline();
var gatekeepers = readline().split(" ").map(function(x) { return { number: parseInt(x), flag: 1} });
var defencemen = readline().split(" ").map(function(x) { return { number: parseInt(x), flag: 2} });
var forwards = readline().split(" ").map(function(x) { return { number: parseInt(x), flag: 3} });
var numberOfTeams = 0;
var allTeams = gatekeepers.concat(defencemen, forwards).sort(function(a,b) {return a.number - b.number});

function combinationOf1(N) {
	return N;
}

function combinationOf2(N) {
	return N*(N-1)/2;
}

function combinationOf3(N) {
	return N*(N-1)*(N-2)/(3*2);
}

for(var i = 0; i < allTeams.length - 5; i++) {
	var lastCheckedIndex = -1;

	for(var k = i + 5; k < allTeams.length; k++) {
		if(allTeams[k].number / allTeams[i].number > 2) {
			break;
		} else {
			lastCheckedIndex = k;
		}
	}

	if(lastCheckedIndex < 0) {
		continue;
	}

	var numberOfGKs = 0, numberOfDs = 0, numberOfFs = 0;

	for(var j = i; j <= lastCheckedIndex; j++) {
		switch(allTeams[j].flag) {
			case 1: numberOfGKs++; break;
			case 2: numberOfDs++; break;
			case 3: numberOfFs++; break;
		}
	}

	if(numberOfGKs < 1 || numberOfDs < 2 || numberOfFs < 3) {
		continue;
	}

	switch(allTeams[i].flag) {
		case 1: numberOfTeams += combinationOf2(numberOfDs)*combinationOf3(numberOfFs); break;
		case 2: numberOfTeams += combinationOf1(numberOfGKs)*combinationOf1(numberOfDs - 1)*combinationOf3(numberOfFs); break;
		case 3: numberOfTeams += combinationOf1(numberOfGKs)*combinationOf2(numberOfDs)*combinationOf2(numberOfFs - 1); break;
	}
}

write(numberOfTeams);


In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.You are given an integer array $$$a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$$$.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[3, 4, 4]$$$ currently in the deque, adding an element $$$1$$$ to the beginning will produce the sequence $$$[\color{red}{1}, 3, 4, 4]$$$, and adding the same element to the end will produce $$$[3, 4, 4, \color{red}{1}]$$$.The elements of the array are sequentially added to the initially empty deque, starting with $$$a_1$$$ and finishing with $$$a_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or to the end.For example, if we consider an array $$$a = [3, 7, 5, 5]$$$, one of the possible sequences of actions looks like this: $$$\quad$$$ 1.add $$$3$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{3}]$$$ in it;$$$\quad$$$ 2.add $$$7$$$ to the end of the deque:deque has a sequence $$$[3, \color{red}{7}]$$$ in it;$$$\quad$$$ 3.add $$$5$$$ to the end of the deque:deque has a sequence $$$[3, 7, \color{red}{5}]$$$ in it;$$$\quad$$$ 4.add $$$5$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{5}, 3, 7, 5]$$$ in it;Find the minimal possible number of inversions in the deque after the whole array is processed. An inversion in sequence $$$d$$$ is a pair of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$d_i > d_j$$$. For example, the array $$$d = [5, 3, 7, 5]$$$ has exactly two inversions — $$$(1, 2)$$$ and $$$(3, 4)$$$, since $$$d_1 = 5 > 3 = d_2$$$ and $$$d_3 = 7 > 5 = d_4$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases.  The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — array size. The second line of the description contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$-10^9 \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 $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the minimal possible number of inversions in the deque after executing the described algorithm.

NoteOne of the ways to get the sequence $$$[5, 3, 7, 5]$$$ in the deque, containing only two inversions, from the initial array $$$[3, 7, 5, 5]$$$ (the first sample test case) is described in the problem statement. Also, in this example, you could get the answer of two inversions by simply putting each element of the original array at the end of the deque. In this case, the original sequence $$$[3, 7, 5, 5]$$$, also containing exactly two inversions, will be in the deque as-is.

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));

// Binary Indexed Tree

const SIZE = 200005;
const data = Array(SIZE);

function add (i, v) {
	for (++i; i < SIZE; i += i&-i) data[i] += v;
}

function sum (i) {
	let res = 0;
	for (++i; i > 0; i -= i&-i) res += data[i];
	return res;
}

function main () {
	let T = rn();
	while (T--) {
		for (let i = 0; i < SIZE; i++) data[i] = 0;

		const n = rn();
		const a = rna();

		for (let i = 0; i < n; i++) a[i] = [a[i], i];
		a.sort((x, y) => x[0] - y[0]);

		const b = [];
		for (let i = 0, cur = 0; i < n; i++) {
			b[a[i][1]] = i > 0 && (a[i][0] == a[i-1][0]) ? cur : ++cur;
		}

		let ans = 0;
		for (let i = 0; i < n; i++) {
			add(b[i], 1);
			ans += Math.min(sum(b[i] - 1), i + 1 - sum(b[i]));
		}

		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));

// Binary Indexed Tree

const SIZE = 200005;
const data = Array(SIZE);

function add (i, v) {
	let cnt = 0;
	++i;
	while (i < SIZE) {
		data[i] += v;
		i += i&-i;
		if (i == 0)  break;
	}
}

function sum (i) {
	let res = 0;
	++i;
	while (i > 0) {
		res += data[i];
		i -= i&-i;
	}
	return res;
}

function main () {
	let T = rn();
	while (T--) {
		for (let i = 0; i < SIZE; i++) data[i] = 0;

		const n = rn();
		const a = rna();

		for (let i = 0; i < n; i++) a[i] = [a[i], i];
		a.sort((x, y) => x[0] - y[0]);

		const b = [];
		for (let i = 0, cur = 0; i < n; i++) {
			b[a[i][1]] = i > 0 && (a[i][0] == a[i-1][0]) ? cur : ++cur;
		}

		let ans = 0;
		for (let i = 0; i < n; i++) {
			add(b[i], 1);
			ans += Math.min(sum(b[i] - 1), i + 1 - sum(b[i]));
		}

		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));

// Binary Indexed Tree

const SIZE = 2**20;
const data = Array(SIZE);

function add (i, v) {
	let cnt = 0;
	++i;
	while (i <= SIZE) {
		if (!data[i]) data[i] = 0;
		data[i] += v;
		i += i&-i;
		if (i == 0)  break;
	}
}

function sum (i) {
	let res = 0;
	++i;
	while (i > 0) {
		if (!data[i]) data[i] = 0;
		res += data[i];
		i -= i&-i;
	}
	return res;
}

function main () {
	let T = rn();
	while (T--) {
		for (let i = 0; i <= SIZE; i++) data[i] = 0;

		const n = rn();
		const a = rna();

		for (let i = 0; i < n; i++) a[i] = [a[i], i];
		a.sort((x, y) => x[0] - y[0]);

		const b = [];
		for (let i = 0, cur = 0; i < n; i++) {
			b[a[i][1]] = i > 0 && (a[i][0] == a[i-1][0]) ? cur : ++cur;
		}

		let ans = 0;
		for (let i = 0; i < n; i++) {
			add(b[i], 1);
			ans += Math.min(sum(b[i] - 1), i + 1 - sum(b[i]));
		}

		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));

// Binary Indexed Tree

const SIZE = 2**19;
const data = Array(SIZE);

function add (i, v) {
	let cnt = 0;
	++i;
	while (i <= SIZE) {
		if (!data[i]) data[i] = 0;
		data[i] += v;
		i += i&-i;
		if (i == 0)  break;
	}
}

function sum (i) {
	let res = 0;
	++i;
	while (i > 0) {
		if (!data[i]) data[i] = 0;
		res += data[i];
		i -= i&-i;
	}
	return res;
}

function main () {
	let T = rn();
	while (T--) {
		for (let i = 0; i <= SIZE; i++) data[i] = 0;

		const n = rn();
		const a = rna();

		for (let i = 0; i < n; i++) a[i] = [a[i], i];
		a.sort((x, y) => x[0] - y[0]);

		const b = [];
		for (let i = 0, cur = 0; i < n; i++) {
			b[a[i][1]] = i > 0 && (a[i][0] == a[i-1][0]) ? cur : ++cur;
		}

		let ans = 0;
		for (let i = 0; i < n; i++) {
			add(b[i], 1);
			ans += Math.min(sum(b[i] - 1), i + 1 - sum(b[i]));
		}

		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));

// Binary Indexed Tree

const SIZE = 2**18;
//const data = Array(SIZE + 1).fill(0);
let data = Array(SIZE);

function add (i, v) {
	let cnt = 0;
	++i;
	while (i <= SIZE) {
		if (!data[i]) data[i] = 0;
		data[i] += v;
		i += i&-i;
		if (i == 0)  break;
	}
}

function sum (i) {
	let res = 0;
	++i;
	while (i > 0) {
		if (!data[i]) data[i] = 0;
		res += data[i];
		i -= i&-i;
	}
	return res;
}

function main () {
	let T = rn();
	while (T--) {
		//data = Array(SIZE);
		for (let i = 0; i <= SIZE; i++) data[i] = 0;

		const n = rn();
		const a = rna();

		for (let i = 0; i < n; i++) a[i] = [a[i], i];
		a.sort((x, y) => x[0] - y[0]);

		const b = [];
		for (let i = 0, cur = 0; i < n; i++) {
			b[a[i][1]] = i > 0 && (a[i][0] == a[i-1][0]) ? cur : ++cur;
		}

		let ans = 0;
		for (let i = 0; i < n; i++) {
			add(b[i], 1);
			ans += Math.min(sum(b[i] - 1), i + 1 - sum(b[i]));
		}

		console.log(ans);
	}
}


Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$="abac", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: "ab", "ba", "ac". Therefore, the string $$$b$$$="abbaac".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.

The first line contains a single positive integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case consists of one line in which the string $$$b$$$ is written, consisting of lowercase English letters ($$$2 \le |b| \le 100$$$) — the string Bob came up with, where $$$|b|$$$ is the length of the string $$$b$$$. It is guaranteed that $$$b$$$ was built according to the algorithm given above.

Output $$$t$$$ answers to test cases. Each answer is the secret string $$$a$$$, consisting of lowercase English letters, that Bob came up with.

NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string $$$a$$$="ac", the string $$$a$$$ has a length $$$2$$$, so the string $$$b$$$ is equal to the string $$$a$$$.In the third test case, Bob came up with the string $$$a$$$="bcdaf", substrings of length $$$2$$$ of string $$$a$$$ are: "bc", "cd", "da", "af", so the string $$$b$$$="bccddaaf".

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() {
    let t = parseInt(readLine());
    while(t--) {
        let ans = "";
        let str = readLine();
        ans += str[0];
        ans += str[1];
        for(let i = 2; i < str.length; i++) {
            if (i%2 !== 0) {
                ans += str[i];
            }
        }
        console.log(ans);
    }
}

process.stdin.setEncoding('utf8');

function solve(input) {
    let data = [];

    for (let i = 0; i < input.length - 1; i += 2) {
        data.push(input[i]);
    }

    data.push(input[input.length - 1]);

    return data;
}

let input = '';

process.stdin.on('data', chunk => {
    if (chunk.trim() == 'end') process.stdin.emit('end');
    else input += chunk;
});

process.stdin.on('end', () => {
    input = input.trim().split('\n').slice(1);

    for (let i = 0; i < input.length; i++) {
        console.log( solve(input[i].trim()).join(''));
    }

    process.exit(0);
});

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

  function solve(str) {
    let output = str[0];
    if (str.length === 2) return str;
    for (let i = 1; i < str.length - 1; i += 2) {
      output += str[i];
    }
    output += str[str.length - 1];
    return output;
  }
}

//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var s = next();
		var n = s[0];
		for(var j = 1; j < s.length - 1; j = j + 2){
			n += s[j];
		}
		n += s[s.length - 1];
		output[i] = n;
	}
	myout(myconv(output,9));
}

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

let stdinInput = '';

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

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 1;
    let i = 1;
    while (i <= testCases) {
        let k = data[i];
        const len = k.length;
        if (len === 2) {
            console.log(k);
            i += 1;
            continue;
        }
        let str = '';
        for (let i = 0; i <= len - 2; i += 2) str += k[i];
        str += k[len - 2];
        console.log(str);
        i += 1;
    }
}

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

let input = '';
process.stdin.on('data', (line) => {
    input += line;
});

process.stdin.on('end', () => {
    const lines = input.split('\n');
    let tests = parseInt(lines.shift(), 10);
    while(tests--) {
        const b = lines.shift();
        const a = b
            .split('')
            .filter((_, index) => {
                return index === 0 ||
                    index === b.length - 1 ||
                    index % 2
                }
            ).join('');
        console.log(a);
    }
});

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

function main(input) {
    let lines = input.trim().split('\n')
    lines.shift()
    for(let line of lines) {
        console.log(solution(line))
    }
}

function solution(line) {
    let ans = line[0]
    for(let i = 1; i < line.length - 1; i += 2) {
        ans += line[i]
    }
    ans += line[line.length - 1]
    return ans
}

function solve(s) {
  const result = [];
  result.push(s[0]);
  for (let i = 2; i < s.length; i = i + 2) {
    result.push(s[i]);
  }
  if ((s.length % 2) === 0) {
    result.push(s[s.length - 1]);
  }
  return result.join('');
}

function main(lines) {
  lines.shift();
  for (const line of lines) {
    let t = line.trim();
    if (line.length > 0) {
      const result = solve(t);
      console.log(result);
    }
  }
}

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding("utf-8");
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
}

processLinesFromStream(process.stdin, main);

function solve(s) {
  const result = [];
  result.push(s[0]);
  for (let i = 2; i < s.length; i = i + 2) {
    result.push(s[i]);
  }
  if ((s.length % 2) === 0) {
    result.push(s[s.length - 1]);
  }
  return result.join('');
}

function main(lines) {
  lines.shift();
  for (const line of lines) {
    const result = solve(line);
    console.log(result);
  }
}

function trim_line(s) {
  return s.trim();
}

function has_content(s) {
  return (s.length > 0);
}

async function processLinesFromStream(rs, pf) {
  const chunks = [];
  const encoding = 'utf-8';
  rs.setEncoding(encoding);
  for await (let chunk of rs) {
    chunks.push(chunk);
  }
  const empty = '';
  const newline = /\n/;
  const lines = chunks.join(empty)
                      .split(newline)
                      .map(trim_line)
                      .filter(has_content);
  const result = pf(lines);
  return result;
}

processLinesFromStream(process.stdin, main);

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

let inputData = '';
let currentLine = 0;

function input() {
  return inputData[currentLine++];
}

process.stdin.on('data', _ => inputData += _);

process.stdin.on('end', () => {
  inputData = inputData.split(/\s+/);
  let noOfTestcases = input();
  let outputString = '';
  while (noOfTestcases--) {
    let str = input();

    outputString += originalWord(str) + '\n';
  }
  process.stdout.write(outputString);
  // console.log(inputData);

});

function originalWord(str) {
  if (str.length <= 2) return str;
  let newStr = str[0];
  for (let i = 1; i < str.length - 1; i = i + 2) {
    let char = str[i];
    newStr += char;

  }
  newStr += str[str.length - 1]
  return newStr;
}

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

var input  = []
rl.on('line', function(line){
    input.push(line);
})

rl.on("close", ContestResponse);

function ContestResponse(){
    let index = 0;
    let nbCases= +input[index++]
    for (let i = 0; i < nbCases; i++){
      let str = input[index++]
      let ret = str[0];
      for (let i = 0; i < str.length - 1; i = i + 2){
        ret += str[i + 1]
      }
      console.log(ret);
    }
}

// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

/**
 *
 * @param {*} str
 * @param {*} seperator
 */
function splitter(str, seperator = '') {
    return str.trim().split(seperator);
}

/**
 *
 * @param {*} arr
 */
function strToNumArr(arr = []) {
    return arr.map(num => Number(num));
}

/**
 *
 * @param {*} num1
 * @param {*} num2
 */
function matrixArray(num1, num2) {
    return Array(num1).fill(Array(num2));
}

let log = function () {
    return Function.prototype.bind.call(console.log, console, '');
}();

function removeEmptyItem(arr, index) {
    return arr.slice(0, index).concat(arr.slice(index + 1, arr.length));
}

function range(min, max) {

    let arr = [];
    for (let index = min; index < max; index++) {
        arr.push(index);

    }
    return arr;
}

function main(input) {
    let output = nameLookUp(input);
    //process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let t = +inputs[0].trim();
    for (let index = 1; index <= t; index++) {
        const element = inputs[index].trim();
        if (element.length > 2) {
            let sliceElement = element.slice(1, element.length - 1);
            let newElem = element[0];
            for (let index2 = 0; index2 < sliceElement.length; index2 += 2) {
                const elem = sliceElement[index2];
                newElem += elem;
            }
            newElem += element[element.length - 1];
            console.log(newElem);
        }
        else {
            console.log(element);
        }
    }
}

'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++];
}
/**
4
abbaac
ac
bccddaaf
zzzzzzzzzz
**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function main() {
    let range = parseInt(readline());

    for(let r = 0;r<range;r++) {
        solve();
    }
}

function solve() {
    let a = readline().split("");
    let n = a.length;

    let string = a[0];
    for(let i=1;i<n-1;i=i+2) {
        if(a[i] === a[i+1]) {
            string+= a[i];
        }else {
            string = a[i] + a[i+1];
        }
    }

    string += a[n-1];
    console.log(string);
}

var t = parseInt(readline());
for (var tc = 0; tc < t; tc++) {
  var str = readline();
  var res = "";
  for (var i = 0; i < str.length; i++) {
    if (i == 0) {
      res += str[i];
      continue;
    }
    if (str[i] == str[i + 1]) {
      res += str[i];
      i++;
    } else res += str[i];
  }
  print(res);
}

var lines = readline();

while(lines--){
    var strA = '';
    var str = Array.from(readline());
    for (var i = 1; i < str.length; i+=2) {
        strA += str[i];
    }
    print(str[0]+strA);
}

"use strict";

//readline().split(' ').map(Number);

function sec(){
    var stri = readline();
    write(stri[0]);
    for (var i=1; i< (stri.length)-1; i+= 2){
        write(stri[i]);
    }
    print(stri[stri.length -1]);
}

function main(){
    var t = readline();
    while(t--){
        sec();
    }
}

main();

function solve() {
   var T = Number(read());
   for (var t = 0; t < T; ++t) {
      var b = read();
      var n2 = Math.round(b.length / 2);
      var a = b[0];
      for (var i = 0; i < n2 - 1; ++i) {
         a = a + b[i * 2 + 1];
      }
      a = a + b[b.length - 1];
      write(a);
   }
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         solve();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', solve);
   }
} else {
   solve();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

function solve(str) {
    var res = str.substr(0,2);
    for (var i=3; i<str.length; i+=2)
        res += str[i];
    return res;
}
var t = Number(readline());
while (t--) {
    var str = readline();
    print(solve(str));
}

process.stdin.setEncoding('utf8');

process.stdin.on('readable', () => {
    let input = process.stdin.read();
    input = input.trim();
    input = input.split('\n').slice(1);

    main(input);
});

function main(input) {
    for (let i = 0; i < input.length; i++) {
        console.log(solve(input[i]).join(''));
    }
    process.exit(0);
}

function solve(input) {
    let data = [];

    for (let i = 0; i < input.length - 1; i += 2) {
        data.push(input[i]);
    }

    data.push(input[input.length - 1]);

    return data;
}


You have a sequence $$$a$$$ with $$$n$$$ elements $$$1, 2, 3, \dots, k - 1, k, k - 1, k - 2, \dots, k - (n - k)$$$ ($$$k \le n < 2k$$$).Let's call as inversion in $$$a$$$ a pair of indices $$$i < j$$$ such that $$$a[i] > a[j]$$$.Suppose, you have some permutation $$$p$$$ of size $$$k$$$ and you build a sequence $$$b$$$ of size $$$n$$$ in the following manner: $$$b[i] = p[a[i]]$$$.Your goal is to find such permutation $$$p$$$ that the total number of inversions in $$$b$$$ doesn't exceed the total number of inversions in $$$a$$$, and $$$b$$$ is lexicographically maximum.Small reminder: the sequence of $$$k$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$k$$$ exactly once.Another small reminder: a sequence $$$s$$$ is lexicographically smaller than another sequence $$$t$$$, if either $$$s$$$ is a prefix of $$$t$$$, or for the first $$$i$$$ such that $$$s_i \ne t_i$$$, $$$s_i < t_i$$$ holds (in the first position that these sequences are different, $$$s$$$ has smaller number than $$$t$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$k \le n < 2k$$$; $$$1 \le k \le 10^5$$$) — the length of the sequence $$$a$$$ and its maximum. It's guaranteed that the total sum of $$$k$$$ over test cases doesn't exceed $$$10^5$$$.

For each test case, print $$$k$$$ integers — the permutation $$$p$$$ which maximizes $$$b$$$ lexicographically without increasing the total number of inversions. It can be proven that $$$p$$$ exists and is unique.

NoteIn the first test case, the sequence $$$a = [1]$$$, there is only one permutation $$$p = [1]$$$.In the second test case, the sequence $$$a = [1, 2]$$$. There is no inversion in $$$a$$$, so there is only one permutation $$$p = [1, 2]$$$ which doesn't increase the number of inversions.In the third test case, $$$a = [1, 2, 1]$$$ and has $$$1$$$ inversion. If we use $$$p = [2, 1]$$$, then $$$b = [p[a[1]], p[a[2]], p[a[3]]] = [2, 1, 2]$$$ and also has $$$1$$$ inversion.In the fourth test case, $$$a = [1, 2, 3, 2]$$$, and since $$$p = [1, 3, 2]$$$ then $$$b = [1, 3, 2, 3]$$$. Both $$$a$$$ and $$$b$$$ have $$$1$$$ inversion and $$$b$$$ is the lexicographically maximum.

/*
 * File Created: Thursday, 14th January 2021 3:54:21 pm
 * Author: Lukas Rimkus
 */

'use-strict'

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

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(readLine(), 10);

    while(testCases--) {

        const [n, k] = readLine().split(' ').map(Number);

        const res = c(n,k);

        console.log(res.join(" "));
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

function readLine() {
        return data[currentLine++];
}

function a(n, d, arr){

    arr.sort((a,b) => a - b);
    // console.log(arr)
    for(let i = 0; i < n ; i++){
        if(arr[i] <= d) continue;
        if(arr[i] > d){
            if(arr[0] + arr[1] <= d && i !== 0 && i !== 1 ){
                continue;
            }
            if(i === 0){
                if(arr[1] + arr[2] <= d) continue;
            }
            if(i === 1){
                if(arr[0] + arr[2] <= d) continue;
            }
        }
        return 'NO'
    }
    return 'YES'
}

function gcd(a,b){
    if(b === 0) return a;
    else{
        return gcd(b, a % b)
    }
}

function lcm(a,b){
    return (a * b) / gcd(a,b)
}

function mul(s, k) {
    let res = '';
    while(k--) res += s;
    return res;
}

function b(s,t){
    const n = s.length;
    const m = t.length;
    const g = gcd(n,m);
    // console.log('gcd(n,m) = ',g,'mul(s,m/g) = ', mul(s, m/ g), 'mul(t,n/g) = ', mul(t, n / g), 'm/g = ', m/g, 'n/g = ', n/g)
    if(mul(s,m /g) === mul(t, n / g)){
        return mul(s, m / g);
    } else {
        return -1;
    }
}

function c(n ,k){
    let ans = [];
    for(let i = 1; i < (k - (n - k)); i++){
        ans.push(i);
    }
    for(let i = k ; i >= (k - (n - k)); i--){
        ans.push(i);
    }
    return ans
}

module.exports = c;

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));

const seq = (s, e) => Array.from(Array(e - s + 1), (_, i) => s + i);

function main () {
	let T = rn();
	while (T--) {
		let [n, k] = rna();

		const x = 2 * k - n - 1;
		const ans = [...seq(1, x), ...seq(x + 1, k).reverse()];

		console.log(ans.join(' '));
	}
}