Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
t=int(input()) for i in range(t): n=int(input()) b=[0]*(2*n) a=list(map(int,input().split())) if 1 not in a: print(-1) else: f=0 s=set() for i in range(n): if a[i]>=2*n: f=1 break else: b[2*i]=a[i] s.add(a[i]) fl=[] for i in range(1,2*n+1): if i not in s: fl.append(i) fl.sort() for i in range(n): ind=0 while(fl[ind]<b[2*i]): ind+=1 if ind ==n: break if ind==n: break b[2*i+1]=fl[ind] fl[ind]=0 if f==1 or 0 in b: print(-1) else: print(*b,sep=" ")
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.*; import java.util.StringTokenizer; import java.util.TreeSet; public class A { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int TC = sc.nextInt(); while (TC --> 0) { int n = sc.nextInt(); TreeSet<Integer> set = new TreeSet<>(); for (int i = 1; i <= 2 * n; i++) { set.add(i); } int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); set.remove(a[i]); } StringBuilder ans = new StringBuilder(); for (int i = 0; i < n; i++) { ans.append(a[i]).append(" "); Integer ceil = set.ceiling(a[i]); if (ceil != null) { set.remove(ceil); ans.append(ceil).append(" "); } else { ans = new StringBuilder(); ans.append(-1); break; } } out.println(ans.toString()); } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));} public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine()throws IOException{return br.readLine();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar()throws IOException{return next().charAt(0);} public Long nextLong()throws IOException{return Long.parseLong(next());} public boolean ready() throws IOException{return br.ready();} public void waitForInput() throws InterruptedException {Thread.sleep(3000);} } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.Scanner; public class C1315 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int ntc = sc.nextInt(); while(ntc-->0){ int n = sc.nextInt(); int[] arr = new int[n]; int twiceN = 2*n +1; int[] arrTwice = new int[twiceN]; arrTwice[0] = -1; StringBuilder ansString = new StringBuilder(); boolean hasAns = true; for(int i = 0;i<n;i++){ arr[i] = sc.nextInt(); } for(int i=0;i<n;i++){ arrTwice[arr[i]] = -1; } int j; for(int i=0;i<n;i++){ ansString.append(arr[i]+" "); for(j=arr[i]+1;j<twiceN;j++){ if(arrTwice[j]!=-1){ ansString.append(j+" "); arrTwice[j]=-1; break; } } if(j == twiceN){ hasAns = false; break; } } if(!hasAns){ System.out.println(-1); }else{ System.out.println(ansString); } } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.*; import java.util.*; import java.math.*; public class C { public void realMain() throws Exception { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000); String in = fin.readLine(); String[] ar = in.split(" "); int T = Integer.parseInt(ar[0]); for(int t = 0; t < T; t++) { in = fin.readLine(); int n = Integer.parseInt(in); in = fin.readLine(); int[] b = new int[n]; ar = in.split(" "); for(int i = 0; i < n; i++) { b[i] = Integer.parseInt(ar[i]); } int[] a = new int[2 * n]; boolean[] used = new boolean[2*n + 1]; for(int i = 0; i < n; i++) { a[2*i] = b[i]; used[b[i]] = true; } for(int i = 1; i < 2*n; i+=2) { int min = a[i - 1] + 1; for(int j = 0; j + min <= 2*n; j++) { if( !used[j + min] ) { a[i] = j + min; used[j + min] = true; break; } } } boolean[] newused = new boolean[2*n + 1]; for(int i = 0; i < 2*n; i++) { newused[a[i]] = true; } boolean win = true; for(int i = 1; i < 2*n + 1; i++) { if(!newused[i]) { win = false; } } if(!win) { System.out.println(-1); } else { for(int i = 0; i < 2*n; i++) { System.out.print(a[i] + " "); } System.out.println(); } } } public static void main(String[] args) throws Exception { C c = new C(); c.realMain(); } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for _ in range(int(input())): n = int(input()) lst = list(map(int,input().split())) lst2 = [] for i in range(1,2*n+1): lst2.append(i) if max(lst) < len(lst): print(-1) else: for i in lst: lst2.remove(i) lst3 = [] lst4 = [False] * n for i in lst: for j in lst2: if i < j and lst4[lst2.index(j)] == False: lst3.append(i) lst3.append(j) lst4[lst2.index(j)] = True break if len(lst3) == 2*n: print(" ".join(map(str,lst3))) else: print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; bool present[1000] = {0}; int main(int argc, char **argv) { int t; cin >> t; while (t--) { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) cin >> arr[i]; for (int i = 1; i <= 2 * n; i++) present[i] = false; for (int i = 0; i < n; i++) present[arr[i]] = true; vector<int> choose; for (int i = 1; i <= 2 * n; i++) if (!present[i]) choose.push_back(i); vector<int> result; bool possible = true; for (int i = 0; i < n; i++) { auto idx = lower_bound(choose.begin(), choose.end(), arr[i]); if (idx == choose.end()) { possible = false; } else { result.push_back(*idx); choose.erase(idx); } } if (!possible) { cout << -1 << endl; } else { for (int i = 0; i < n; i++) cout << arr[i] << " " << result[i] << " "; cout << endl; } } return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
""" Author - Satwik Tiwari . 27th Oct , 2020 - Tuesday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def zerolist(n): return [0]*n def nextline(): out("\n") #as stdout.write always print sring. def testcase(t): for pp in range(t): solve(pp) def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,20) mod = 10**9+7 #=============================================================================================== # code here ;)) def solve(case): n = int(inp()) a = lis() if(1 not in a): print(-1) return if(len(set(a)) != n): print(-1) return vis = [0]*(2*n+1) ans = [-1]*(2*n) for i in range(n): vis[a[i]] = 1 ans[2*i] = a[i] # print(ans) # print(vis) for i in range(1,2*n,2): for j in range(ans[i-1]+1,2*n+1): if(vis[j] == 0): ans[i] = j vis[j] = 1 break for i in range(1,2*n+1): if(vis[i] == 0): print(-1) return print(' '.join(str(ans[i]) for i in range(2*n))) # testcase(1) testcase(int(inp()))
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import sys from collections import Counter def solve(N, B): counts = Counter(B) if any(v > 1 for v in counts.values()): return -1 # Want smallest permutation that is element-wise greater than B C = [] for x in range(1, 2 * N + 1): if x not in counts: C.append(x) # Sorted B and C must be pairable if any(b > c for b, c in zip(sorted(B), C)): return -1 # Brute force with early exit to find min permutation # This passed but I am not sure if it's the intended solution? def gen(index=0): if index == N: yield C return for c, i in sorted(zip(C[index:N], range(index, N))): if B[index] < c: C[index], C[i] = C[i], C[index] yield from gen(index + 1) # Turns out this is never reached... assert False C[index], C[i] = C[i], C[index] for sol in gen(): A = [] for b, c in zip(B, C): A.append(str(b)) A.append(str(c)) return " ".join(A) return -1 if __name__ == "__main__": input = sys.stdin.readline T = int(input()) for t in range(T): N, = map(int, input().split()) B = [int(x) for x in input().split()] ans = solve(N, B) print(ans)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) tree = list(range(2*n+10)) def find(st): if tree[st]!=st: tree[st] = find(tree[st]) return tree[st] for c in arr: tree[find(c)] = find(c+1) ans = [0]*(2*n) for i in range(0,2*n,2): ans[i] = arr[i//2] f = True for i in range(1,2*n,2): d = ans[i-1] ans[i] = find(d) tree[ans[i]] = find(ans[i]+1) if ans[i]>2*n: f = False break if f: print(*ans) else: print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
from collections import Counter from collections import defaultdict import math t=int(input()) for _ in range(0,t): n=int(input()) a=list(map(int,input().split())) l=list() k=1 d=defaultdict(lambda:0) for i in range(0,n): d[a[i]]=1 for i in range(0,n): f=0 for j in range(a[i]+1,2*n+1): if(d[j]==0): f=1 d[j]=1 l.append(a[i]) l.append(j) break if(f==0): k=0 print(-1) break if(k==1): print(*l)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; long long t, n, i, j, k, a, b, c, m, l, r, s; void dihan() { cin >> n; vector<long long> x(n); for (auto &i : x) cin >> i; vector<long long> y(2 * n + 1); for (i = 0; i < n; i++) y[x[i]] = i + 1; priority_queue<long long> q; vector<pair<long long, long long> > p; for (i = 1; i < 2 * n + 1; i++) if (y[i] != 0) q.push(-y[i]); else if (q.size() > 0) { y[i] = -q.top(); q.pop(); } else { cout << -1 << endl; return; } for (i = 1; i < 2 * n + 1; i++) p.push_back({y[i], i}); sort(p.begin(), p.end()); for (auto i : p) cout << i.second << " "; cout << endl; } int main() { ios::sync_with_stdio(0); cin.tie(nullptr); cin >> t; while (t--) dihan(); }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
def find(st, num): mn = -1 for i in st: if mn == -1: if i > num: mn = i else: if num < i < mn: mn = i return mn def main(): n = int(input()) st = set() for i in range(1, (n * 2) + 1): st.add(i) lst = list(map(int, input().split())) for i in lst: if not i in st: break st.remove(i) line = "" for i in lst: elem = find(st, i) if elem == -1: print(-1) return line += str(i) + " " + str(elem) + " " st.remove(elem) print(line) if __name__ == "__main__": t = int(input()) for i in range(t): main()
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz' M=10**9+7 EPS=1e-6 def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() for _ in range(Int()): n=Int() a=array() ans=[0]*(2*n) have=[] ok=True for i in range(1,2*n+1): if(i not in a): have.append(i) # print(a) # print(have) for i in range(n): # print(2*i,2*i+1,ans) ans[2*i]=a[i] ind=bisect_left(have,a[i]) try: ans[2*i+1]=have[ind] have.remove(have[ind]) except: ok=False if(ok): print(*ans) else: print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; const int N = int(2e5 + 20); const int INF = int(1e9 + 5); const long long LINF = int(1e18 + 20); int main() { int t; cin >> t; for (; t; t--) { int n; cin >> n; set<int> ok; for (int i = 1; i <= 2 * n; i++) ok.insert(i); vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; ok.erase(a[i]); } vector<int> b(2 * n); for (int i = 0; i < 2 * n; i += 2) { b[i] = a[i / 2]; } bool f = 0; for (int i = 1; i < 2 * n; i += 2) { if (ok.lower_bound(b[i - 1]) == ok.end()) { f = 1; break; } b[i] = *ok.lower_bound(b[i - 1]); ok.erase(ok.lower_bound(b[i - 1])); } if (f) { cout << "-1\n"; continue; } for (int i = 1; i < 2 * n; i += 2) for (int j = i + 2; j < 2 * n; j += 2) { if (b[i] > b[j] && b[i] > b[j - 1] && b[j] > b[i - 1]) swap(b[i], b[j]); } for (auto i : b) cout << i << ' '; cout << '\n'; } }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.*; import java.math.*; import java.util.*; public class Solve { FastScanner in; PrintWriter out; void solve() { int T = in.nextInt(); while (0 < T--) { int n = in.nextInt(); int[] b = in.nextIntArray(n); HashSet<Integer> hs = new HashSet<>(); boolean[] used = new boolean[n*2+1]; for (int i = 0; i < n; i++) { used[b[i]] = true; } int[] a = new int[n*2]; Arrays.fill(a, -1); for (int i = 0; i < n; i++) { a[i*2] = b[i]; int tmp = b[i]+1; while (tmp <= n*2 && used[tmp]) { tmp++; } if (tmp <= n*2 && ! used[tmp]) { a[i*2+1] = tmp; used[tmp] = true; } } boolean ok = true; for (int i = 0; i < n*2; i++) { if (a[i] == -1) { ok = false; break; } } if (ok) { for (int i = 0; i < n*2; i++) { out.print(a[i] + " "); } out.println(); } else { out.println(-1); } // out.println(Arrays.toString(a)); // 4 1 // -1 // bi = min(a2i-1, a2i) // 1 // 1 2 // 4 1 3 b n=3 // 4 5 1 2 3 6 a 2n=6 // * * // * * // * * // 1 5 7 2 8 // 1 3 5 6 7 9 2 4 8 10 } } void run() { try { in = new FastScanner(new File("Solve.in")); out = new PrintWriter(new File("Solve.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } return a; } long nextLong() { return Long.parseLong(next()); } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.nextLong(); } return a; } BigInteger nextBigInteger() { return new BigInteger(next()); } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) { a[i] = in.nextDouble(); } return a; } } public static void main(String[] args) { new Solve().runIO(); } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.*; public class C1315 { public static void main(String args[])throws IOException { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int z=1;z<=t;z++) { int n=sc.nextInt(); int b[]=new int[n]; TreeSet<Integer> set=new TreeSet<>(); for(int i=1;i<=2*n;i++) { set.add(i); } for(int i=0;i<n;i++) { b[i]=sc.nextInt(); set.remove(b[i]); } int a[]=new int[2*n]; int f=0; for(int i=0;i<n;i++) { a[2*i]=b[i]; if(set.higher(b[i])==null) { f=1;break; } int x=set.higher(b[i]); a[2*i +1]=x; set.remove(x); } if(f==1) System.out.println(-1); else { for(int i=0;i<2*n;i++) { System.out.print(a[i]+" "); } System.out.println(); } } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.*; import java.util.*; import java.lang.*; import java.math.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while (t-->0){ int n=Integer.parseInt(br.readLine()); Integer[] b=new Integer[2*n]; String s=br.readLine(); StringTokenizer st=new StringTokenizer(s); for(int i=0;i<2*n;i+=2){ b[i]=Integer.parseInt(st.nextToken()); b[i+1]=b[i]; } Set<Integer> set = new HashSet<Integer>(Arrays.asList(b)); Set<Integer> a=new TreeSet<Integer>(); for(int i=1;i<=2*n;i++){ if(!set.contains(i)){ a.add(i); } } int flag=0; for(int i=1;i<2*n;i+=2){ flag=0; for(int it : a){ if(it>b[i]){ b[i]=it; flag=1; a.remove(it); break; } } if(flag==0){ System.out.println(-1); break; } } if(flag!=0){ for(int i=0;i<2*n;i++) System.out.print(b[i]+" "); System.out.println(); } } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C623 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner obj=new Scanner(System.in); int t=obj.nextInt(); while(t-->0) { int n=obj.nextInt(); Set<Integer> set=new HashSet(); Set<Integer> set2=new HashSet(); int[] arr=new int[n]; for(int i=0;i<n;i++) { arr[i]=obj.nextInt(); set.add(arr[i]); } ArrayList<Integer> a=new ArrayList<>(); for(int i=0;i<n;i++) { for(int j=arr[i]+1;j<=2*n;j++) { if(!set.contains(j)&&(!set2.contains(j))) { //System.out.println("**"); set2.add(arr[i]); set2.add(j); a.add(arr[i]); a.add(j); set.remove(arr[i]); set.remove(j); break; } } } if(set2.size()==2*n) { for(int i=0;i<2*n;i++) { System.out.print(a.get(i)+" "); } System.out.println(); } else System.out.println("-1"); } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.*; import java.io.*; import java.math.*; public class C623{ public static int lower(ArrayList<Integer> a,int x){ int low=0; int high=a.size(); while(low<high){ int mid=(low+high)/2; if(x<=a.get(mid)) high=mid; else low=mid+1; } return low; } public static void main(String args[]){ FastReader sc = new FastReader(); int t,n,i; t=sc.nextInt(); while(t-->0){ n=sc.nextInt(); int b[]=new int[n+1]; int a[]=new int[2*n+1]; int f[]=new int[2*n+1]; Arrays.fill(f,1); for(i=1;i<=n;i++){ b[i]=sc.nextInt(); a[2*i-1]=b[i]; f[b[i]]--; } int flag=1; ArrayList<Integer> sch=new ArrayList<>(); for(i=1;i<=2*n;i++){ if(f[i]==1) sch.add(i); } //out.println(sch); for(i=2;i<=2*n;i+=2){ int idx=lower(sch,a[i-1]); if(idx==sch.size()){ flag=0; break; } else{ a[i]=sch.get(idx); sch.remove(idx); } } if(flag==0){ out.println(-1); continue; } for(i=1;i<=2*n;i++) out.print(a[i]+" "); out.println(); } out.flush(); } static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); } String next(){ while(st==null || !st.hasMoreElements()){ try{ st= new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str = ""; try{ str=br.readLine(); } catch(IOException e){ e.printStackTrace(); } return str; } } public static boolean isPrime(int n) { if(n<2) return false; for(int i=2;i<=(int)Math.sqrt(n);i++) { if(n%i==0) return false; } return true; } public static void print(int a[],int l,int r){ int i; for(i=l;i<=r;i++) out.print(a[i]+" "); out.println(); } public static long fastexpo(long x, long y, long p){ long res=1; while(y > 0){ if((y & 1)==1) res= ((res%p)*(x%p))%p; y= y >> 1; x = ((x%p)*(x%p))%p; } return res; } public static boolean[] sieve (int n) { boolean primes[]=new boolean[n+1]; Arrays.fill(primes,true); primes[0]=primes[1]=false; for(int i=2;i*i<=n;i++){ if(primes[i]){ for(int j=i*i;j<=n;j+=i) primes[j]=false; } } return primes; } public static long gcd(long a,long b){ return (BigInteger.valueOf(a).gcd(BigInteger.valueOf(b))).longValue(); } public static void merge(int a[],int l,int m,int r){ int n1,n2,i,j,k; n1=m-l+1; n2=r-m; int L[]=new int[n1]; int R[]=new int[n2]; for(i=0;i<n1;i++) L[i]=a[l+i]; for(j=0;j<n2;j++) R[j]=a[m+1+j]; i=0;j=0; k=l; while(i<n1&&j<n2){ if(L[i]<=R[j]){ a[k]=L[i]; i++; } else{ a[k]=R[j]; j++; } k++; } while(i<n1){ a[k]=L[i]; i++; k++; } while(j<n2){ a[k]=R[j]; j++; k++; } } public static void sort(int a[],int l,int r){ int m; if(l<r){ m=(l+r)/2; sort(a,l,m); sort(a,m+1,r); merge(a,l,m,r); } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 10**9 + 7 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n').split(' ')] def li3():return [int(i) for i in input().rstrip('\n')] for _ in range(val()): n = val() b = li() a = [0 for i in range(2*n)] for i in range(n): a[2*i] = b[i] s = set([i for i in range(1,2*n + 1)]) for i in b:s.remove(i) for i in range(1,2*n,2): temp = a[i-1] while temp + 1 not in s and temp + 1 <= 2*n:temp += 1 temp += 1 if temp == 2*n + 1: ans = -1 a = -1 break a[i] = temp s.remove(temp) if a != -1:print(*a) else:print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
t = int(input()) for _ in range(t): n = int(input()) b = list(map(int, input().split())) c = set(b) l = [] valid = True for i in b: temp = i + 1 while temp in c: temp += 1 if temp > 2*n: print(-1) valid = False break l += [i, temp] c.add(temp) if valid: print(' '.join(map(str, l)))
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
T = int(input().strip()) debug = False for t in range(T): N = int(input().strip()) A = list(map(int, input().split())) totalSum = 2*N*(2*N+1)/2 total=0 d={} for a in A: d[a]=1 B = [] for a in A: B.append(a) total+=a x=a while True: x = x+1 if x not in d: d[x]=1 B.append(x) total+=x break if total==totalSum: print(*B) else: print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Problem623C { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int testCases = Integer.parseInt(reader.readLine()); for (int t = 0; t < testCases; t++) { int n = Integer.parseInt(reader.readLine()); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int[] b = new int[n]; for (int i = 0; i < n; i++) { b[i] = Integer.parseInt(tokenizer.nextToken()); } writer.println(solve(b)); } writer.close(); } public static String solve(int[] b) { StringBuilder builder = new StringBuilder(); int n = b.length; boolean[] nums = new boolean[2 * n + 5]; for (int i : b) { nums[i] = true; } for (int i = 0; i < b.length; i++) { builder.append(b[i]); builder.append(' '); boolean flag = false; for (int j = b[i] + 1; j <= 2 * n; j++) { if (!nums[j]) { builder.append(j); builder.append(' '); nums[j] = true; flag = true; break; } } if (!flag) { return "-1"; } } return builder.toString().substring(0, builder.length() - 1); } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; int a[101], ac[202]; void solve() { int n; cin >> n; bool f = 0; memset(ac, 0, sizeof(ac)); for (int i = 0; i < n; i++) { cin >> a[i]; ac[a[i]] = 1; } if (ac[1] == 0) { f = 1; } vector<int> v; for (int i = 0; i < n; i++) { bool k = 0; for (int j = a[i] + 1; j <= 2 * n; j++) { if (ac[j] == 0) { ac[j] = 1; k = 1; v.push_back(a[i]); v.push_back(j); break; } } if (k == 0) { f = 1; break; } } if (f) { cout << "-1\n"; return; } else { for (int i : v) { cout << i << " "; } } cout << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long t = 1; cin >> t; while (t--) { solve(); } return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for _ in range(int(input())): n=int(input()) u=False s=[] k=[] l=list(map(int,input().split())) for i in range(1,2*n+1): if i not in l: k.append(i) #print(k) for i in range(n): s.append(l[i]) for j in range(len(k)): #print(k[j],l[i]) if k[j]>l[i]: s.append(k[j]) del k[j] u=True break if not u: print("-1") break if u and len(s)==2*n: print(*s,sep=" ") elif u: print("-1")
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; const double PI = atan(1.0) * 4; const int64_t INF = 100000000000000003; const int32_t LOG = 21; const int MOD = 1e9 + 7; int32_t main() { ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); int tests = 1; cin >> tests; for (int ii = 0; ii < tests; ii++) { int n; cin >> n; vector<int> v(2 * n, 0); int b[n]; for (int i = 0; i < n; i++) { cin >> b[i]; } set<int> second; for (int i = 1; i < 2 * n + 1; i++) second.insert(i); for (int i = 0; i < n; i++) { v[2 * i] = b[i]; second.erase(b[i]); } bool g = true; for (int i = 0; i < n; i++) { int x = v[2 * i]; auto it = second.lower_bound(x); if (it == second.end()) { g = false; break; } v[2 * i + 1] = *it; second.erase(v[2 * i + 1]); } if (!g) cout << -1 << '\n'; else { for (int i = 0; i < 2 * n; i++) cout << v[i] << " "; cout << '\n'; } } return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for tin in range(int(input())): n=int(input()) b=list(map(int,input().split())) c=[0]*(2*n+1) for _ in range(len(b)): c[b[_]]=1 a=[0]*(2*n) v=0 for _ in range(n): a[v]=b[_] x=0 for j in range(b[_],2*n+1): if c[j]!=1: a[v+1]=j c[j]=1 x+=1 break if x==0: break v+=2 if v!=2*n: print(-1) else: for _ in range(2*n-1): print(a[_],end=" ") print(a[-1])
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; int i, j, n, k, t, a[240], b[105], p[240]; int main() { cin >> t; for (k = 1; k <= t; k++) { cin >> n; for (i = 0; i++ < n;) { cin >> b[i]; p[b[i]] = 1; } for (i = 0; i++ < n;) { for (j = b[i]; p[j] && j <= 2 * n;) j++; if (j > 2 * n) { cout << -1 << endl; goto G; } a[2 * i - 1] = b[i]; a[2 * i] = j; p[j] = 1; } for (i = 0; i++ < 2 * n;) cout << a[i] << ' '; cout << endl; G: for (i = 0; i++ < 2 * n;) p[i] = 0; } }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> long double pi = 3.14159265358979; using namespace std; int inf = 1e9; void fastIO() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } void solve() { int n; cin >> n; vector<int> a(2 * n); vector<bool> cur(2 * n, true); for (int i = 0; i < 2 * n; i += 2) { cin >> a[i]; a[i]--; cur[a[i]] = false; } for (int i = 1; i < 2 * n; i += 2) { int pos = inf; for (int j = 2 * n - 1; j >= 0; j--) if (cur[j] && j > a[i - 1]) pos = min(pos, j); if (pos == inf) { cout << -1 << "\n"; return; } a[i] = pos; cur[pos] = false; } for (int i = 0; i < 2 * n; i++) cout << a[i] + 1 << " "; cout << "\n"; return; } int main() { fastIO(); int t; cin >> t; for (int i = 0; i < t; i++) solve(); return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
from collections import defaultdict t = int(input()) for _ in range(t): n = int(input()) b = list(map(int, input().split())) b = list(map(lambda x: x-1, b)) flag = [False]*(2*n) for bi in b: flag[bi] = True pair = defaultdict(int) f = True for bi in b: for i in range(bi+1, 2*n): if not flag[i]: pair[bi] = i flag[i] = True break else: f = False if not f: print(-1) continue ans = [] for bi in b: ans.append(min(bi, pair[bi])) ans.append(max(bi, pair[bi])) ans = list(map(lambda x: x+1, ans)) print(*ans)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
if __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input()) l = [int(i) for i in input().split(' ')] res = [] a = sorted(list(set([i for i in range(1, 2 * n + 1)]) - set(l))) # print(l) # print(a) for i in range(n): cur = l[i] for j in a: if j > cur: res.append(cur) res.append(j) a.remove(j) break # print(res) if len(res) == n * 2: print(' '.join([str(i) for i in res])) else: print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; int t, a[109], n, vis[300]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; cin >> t; while (t--) { cin >> n; memset(vis, 0, sizeof vis); int good = 1; for (int i = 1; i <= n; i++) { cin >> a[i]; vis[a[i]]++; if (vis[a[i]] > 1) good = 0; } if (!good) { cout << -1 << "\n"; continue; } vector<int> v; for (int i = 1; i <= n; i++) { v.push_back(a[i]); for (int j = a[i] + 1; j <= 2 * n; j++) if (!vis[j]) { v.push_back(j); vis[j]++; break; } if ((int)v.size() % 2) break; } if (v.size() != 2 * n) { cout << -1 << "\n"; continue; } for (auto i : v) cout << i << " "; cout << "\n"; } }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
from functools import reduce import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase input = lambda: sys.stdin.readline().rstrip("\r\n") def value():return tuple(map(int,input().split())) def arr():return [int(i) for i in input().split()] def sarr():return [int(i) for i in input()] def inn():return int(input()) mo=1000000007 #----------------------------CODE------------------------------# for _ in range(int(input())): n=inn() a=arr() d=defaultdict(int) ans=[] for i in a: d[i]+=1 for i in range(n): res=a[i] for j in range(a[i]+1,2*n+1): if(j not in d): ans+=[(res,j)] d[j]+=1 break flag=0 for i in range(1,2*n+1): if(i not in d): flag=1 break if(flag==1): print(-1) else: for i in range(n): print(ans[i][0],ans[i][1],end=" ") print()
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
t = int(input()) while t > 0: n = int(input()) b = [int(x) for x in input().split()] a = [0] * (2 * n + 1) for i in b: a[i] = 1 s = [0] * (2 * n + 1) counter = 1 failed = False for i in b: s[counter] = i found = False for j in range(i + 1, 2 * n + 1): if a[j] == 0: s[counter + 1] = j a[j] = 1 found = True break if not found: print("-1") failed = True break counter += 2 if not failed: s = s[1:] print(' '.join(map(str, s))) t -= 1
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
t=int(input()) for l in range(t): n=int(input()) tab=[0 for i in range(2*n)] s=input().split() for k in s: tab[int(k)-1]=1 num=[] for i in s: j=int(i)-1 num.append(j+1) for k in range(j,2*n): if tab[k]==0: tab[k]=1 num.append(k+1) break co=tab.count(0) if co==0: for m in num: print(m,end=" ") print() else: print("-1")
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.*; public class RestoringPermutation{ public static int find(Set<Integer> unusedNums, int a) { int min = 300; for(int i : unusedNums) { if(i > a && i < min) min = i; } return min; } public static void main(String []args){ Scanner s1 = new Scanner(System.in); int t = Integer.parseInt(s1.nextLine()); for(int q = 0; q < t; q++) { int n = Integer.parseInt(s1.nextLine()); String s = s1.nextLine(); String[] sequence = s.split(" "); int[] arr = new int[2*sequence.length]; Set<Integer> usedNums = new HashSet<Integer>(); Set<Integer> unusedNums = new HashSet<Integer>(); for(int i = 0; i < sequence.length; i++) { arr[2*i] = Integer.parseInt(sequence[i]); usedNums.add(Integer.parseInt(sequence[i])); } for(int i = 1; i <= 2*sequence.length; i++) { if(!usedNums.contains(i)) unusedNums.add(i); } for(int i = 0; i < sequence.length; i++) { arr[2*i + 1] = find(unusedNums, arr[2*i]); if(arr[2*i+1] == 300) { System.out.println(-1); break; } unusedNums.remove(arr[2*i+1]); } if(unusedNums.size() ==0){ for(int i = 1; i <= 2*sequence.length; i++) { System.out.print(arr[i-1] + " "); } System.out.println();} } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for _ in range(int(input())): n=int(input()) b=list(map(int,input().split())) done = [0]*(2*n+1) if min(b)!=1 or max(b)==2*n: print(-1) else: ans = [0]*(2*n+1) for i in range(len(b)): done[b[i]]=1 ans[2*i+1] = b[i] # print(ans) for i in range(1,n+1): for j in range(ans[2*i-1]+1,2*n+1): if done[j]==0: ans[2*i]=j done[j]=1 break if 0 in ans[1:]: print(-1) else: print(*ans[1:])
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.*; public class EXPCH { static long modInverse(long a, long m) { long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { long q = a / m; long t = m; m = a % m; a = t; t = y; y = x - q * y; x = t; } if (x < 0) x += m0; return x; } public static class pair implements Comparable<pair>{ int idx,val; public pair(int i,int j) { idx=i; val=j; } @Override public int compareTo(pair o) { // TODO Auto-generated method stub return this.val-o.val; } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int t=sc.nextInt(); StringBuilder st=new StringBuilder(); while(t-->0) { TreeSet<Integer>hs=new TreeSet<>(); int n=sc.nextInt(); int a[]=new int[2*n+1]; pair b[]=new pair[n+1]; b[0]=new pair(0,0); for(int i=1;i<=2*n;i++) { hs.add(i); } for(int i=1;i<=n;i++) { b[i]=new pair(i,sc.nextInt()); hs.remove(b[i].val); } //Arrays.parallelSort(b); boolean f=true; for(int i=1;i<=n;i++) { int val=b[i].val; int idx=b[i].idx; if(hs.ceiling(val+1)==null) { f=false;break; } int no=hs.ceiling(val+1); a[idx*2]=no; a[idx*2-1]=val; hs.remove(no); } if(!f) { st.append(-1+"\n"); continue; } for(int i=1;i<=2*n;i++) { st.append(a[i]+" "); } st.append("\n"); } System.out.println(st); } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; long long M = 1e9 + 7; void solve() { long long int n; cin >> n; vector<long long int> b(n); map<long long int, long long int> mp; set<long long int> st; for (long long int i = 0; i < n; i++) { cin >> b[i]; mp[b[i]]++; } for (long long int i = 1; i <= 2 * n; i++) { if (!mp[i]) st.insert(i); } vector<long long int> a(2 * n, -1); for (long long int i = 0, j = 0; i < 2 * n; i++, j++) { a[i] = b[j]; i++; } for (long long int i = 0; i < 2 * n; i++) { if (a[i] == -1) { if (st.lower_bound(a[i - 1]) == st.end()) { cout << -1 << "\n"; return; } auto it = st.lower_bound(a[i - 1]); a[i] = *it; st.erase(a[i]); } } for (auto x : a) { cout << x << " "; } cout << "\n"; } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; long long int t; cin >> t; while (t--) { solve(); } }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.*; import java.util.*; public class QB_Jan { static class Print { private final BufferedWriter bw; public Print() { this.bw=new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object)throws IOException { bw.append(""+object); } public void println(Object object)throws IOException { print(object); bw.append("\n"); } public void close()throws IOException { bw.close(); } } static class Scan { private byte[] buf=new byte[1024*1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public long scanLong() throws IOException { long ret = 0; long c = scan(); while (c <= ' ') { c = scan(); } boolean neg = (c == '-'); if (neg) { c = scan(); } do { ret = ret * 10 + c - '0'; } while ((c = scan()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void main(String args[]) throws Exception { Scan scan=new Scan(); Print p=new Print(); int T=scan.scanInt(); loop: while (T-->0) { int N=scan.scanInt(); int b[]=new int[N+1]; HashSet<Integer> hashSet=new HashSet<Integer>(); for(int i=1;i<=N;i++) { b[i]=scan.scanInt(); hashSet.add(b[i]); } int a[]=new int[(2*N)+1]; for(int i=1;i<=N;i++) { int temp=b[i]+1; a[2*i-1]=b[i]; while(hashSet.contains(temp)) { temp++; } if(temp>2*N) { p.println("-1"); continue loop; } else { hashSet.add(temp); a[(2*i)]=temp; } } for(int i=1;i<=2*N;i++) { p.print(a[i]+" "); } p.print("\n"); } p.close(); } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import sys from bisect import bisect_left reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ def find_ge(a, x): 'Find leftmost item greater than or equal to x' i = bisect_left(a, x) if i != len(a): return a[i] return False def gift(): for _ in range(cou): n = int(input()) lst= [int(x) for x in input().split()] newlst=lst[:] newlst.sort() less=0 big=0 onein=False bignotin=True error=False full=list(range(1,n*2+1)) for ele in newlst: if ele<=n: less+=1 else: big+=1 if ele==1: onein=True if ele==n*2: bignotin=False full.remove(ele) #print(onein,bignotin,less<big,full) if onein and bignotin and less>=big: res=[] #print(lst,full) for ele in lst: #print(res) found=find_ge(full,ele) #print(found) if not found: error=True break res.append(ele) res.append(found) full.remove(found) if error: yield -1 else: yield " ".join(str(x) for x in res) else: yield -1 if __name__ == '__main__': cou= int(input()) ans = gift() print(*ans,sep='\n')
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.*; import java.io.*; import java.util.Map.*; public class C_1315 { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); big: while(t-->0) { int n = sc.nextInt(); int[] array = sc.nextIntArray(n); TreeSet<Integer> set = new TreeSet<>(); for(int i = 1; i <= n * 2; i++) set.add(i); for(int i = 0; i < n; i++) set.remove(array[i]); int[] ans = new int[n]; for(int i = 0; i < n; i++) { if(set.higher(array[i]) == null) { pw.println(-1); continue big; } int x = set.higher(array[i]); ans[i] = x; set.remove(x); } for(int i = 0; i < n; i++) pw.print(array[i] + " " + ans[i] + (i == n - 1 ? "\n" : " ")); } pw.flush(); } public static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextIntArray(int n) throws IOException { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) array[i] = new Integer(nextInt()); return array; } public long[] nextLongArray(int n) throws IOException { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public double[] nextDoubleArray(int n) throws IOException { double[] array = new double[n]; for (int i = 0; i < n; i++) array[i] = nextDouble(); return array; } public static int[] shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
from sys import stdin, gettrace if not gettrace(): def input(): return next(stdin)[:-1] def main(): def solve(): n = int(input()) bb = [int(a) for a in input().split()] avail = [False] + [True] * 2 * n for b in bb: avail[b] = False res = [] for b in bb: if b == n*2: print(-1) return res.append(b) c = b+1 while not avail[c]: c+=1 if c == 2*n+1: print(-1) return res.append(c) avail[c] = False print(' '.join(map(str, res))) q = int(input()) for _ in range(q): solve() if __name__ == "__main__": main()
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.*; import java.io.*; //odd selsection 1363-A public class CodeForce { public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] b = new int[n]; for (int i = 0; i < b.length; i++) { b[i] = sc.nextInt(); } int[] arr = ultimate(b, n); if (arr == null) System.out.println(-1); else printarr(arr); } } public static void printarr(int[] a) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); } public static int[] ultimate(int[] b, int n) { int[] a = new int[2 * n]; boolean[] vis = new boolean[2 * n + 1]; for (int i = 0; i < b.length; i++) { a[(i + 1) * 2 - 2] = b[i]; vis[b[i]] = true; } for (int i = 1; i < a.length; i += 2) { for (int j = 1; j < vis.length; j++) { if (!vis[j] && j > a[i - 1]) { a[i] = j; vis[j] = true; break; } } } for (int i = 1; i < vis.length; i++) { if (!vis[i]) return null; } return a; } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import sys input = sys.stdin.readline for _ in range(int(input())): n = int(input()) y = [*map(int, input().split())] x = {*range(1, 2*n+1)}.difference(y) res = [] for i in y: a = [j for j in x if i < j] if a: b = min(a) x.remove(b) res.extend([i, b]) else: print(-1) break if not x: print(*res)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; import java.util.Arrays; public class project { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); int t=sc.nextInt(); while(t>0){ int i,m=1,p; int n=sc.nextInt(); int b[]=new int[n]; int a[]=new int[2*n+1]; int f[]=new int[2*n+1]; boolean flag=true; for(i=0;i<n;i++) b[i]=sc.nextInt(); for(i=0;i<n;i++){ a[2*i+1]=b[i]; f[b[i]]++; } for(i=2;i<2*n+1;i=i+2){ m=1; flag=true; while(flag){ if(a[i-1]+m>2*n) {flag=false;break;} else{ if(f[a[i-1]+m]==0) break; else if(f[a[i-1]+m]==1) m++; } } if(!flag) {System.out.print("-1");break;} else{ a[i]= a[i-1]+m; f[a[i-1]+m]++;} } if(flag){ for(i=1;i<2*n+1;i++) System.out.print(a[i]+" ");} System.out.print("\n"); t--; } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> b(n); vector<int> q; unordered_set<int> s; for (int i = 0; i < n; i++) { cin >> b[i]; s.insert(b[i]); } for (int i = 1; i <= 2 * n; i++) { if (s.count(i) == 0) q.push_back(i); } vector<int> perm; bool p = true; for (int i = 0; i < 2 * n && p; i++) { if (i % 2 == 0) { perm.push_back(b[i / 2]); } else { auto it = lower_bound(q.begin(), q.end(), b[i / 2]); if (it == q.end()) { cout << -1 << endl; p = false; } else { perm.push_back(*it); q.erase(it); } } } if (p) { for (int i : perm) { cout << i << " "; } cout << endl; } } }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; double getTime() { return clock() / (double)CLOCKS_PER_SEC; } void read(){}; template <typename T, typename... Args> void read(T& a, Args&... args) { cin >> a; read(args...); } void print(){}; template <typename T, typename... Args> void print(T a, Args... args) { cout << a << " \n"[sizeof...(args) == 0]; print(args...); } void solve() { int n; cin >> n; vector<int> a(n); vector<int> cnt(201, 0); for (int i = 0; i < n; i++) { read(a[i]); cnt[a[i]] = 1; } vector<int> ans; for (int i = 0; i < n; i++) { ans.push_back(a[i]); int k = 1; while (cnt[a[i] + k]) k++; ans.push_back(a[i] + k); cnt[a[i] + k] = 1; if (a[i] + k > n + n) { print(-1); return; } } for (auto x : ans) cout << x << ' '; puts(""); } int main() { int t; read(t); while (t--) solve(); }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; void solve() { int t; cin >> t; while (t--) { int n; cin >> n; int a[n]; int maxi = 2 * n; unordered_map<int, int> map; for (long long i = 0; i < n; i++) { cin >> a[i]; map[a[i]]++; } if (map.count(1) <= 0) { cout << -1 << endl; continue; } if (map.count(maxi) > 0) { cout << -1 << endl; continue; } vector<int> ans; for (int i = 0; i < n; i++) { int greater = -1; for (int j = a[i] + 1; j <= 2 * n; j++) { if (map.count(j) <= 0) { map[j]++; greater = j; break; } } if (greater == -1) { cout << -1; break; } else { ans.push_back(a[i]); ; ans.push_back(greater); ; } } if (ans.size() == 2 * n) { for (long long i = 0; i < ans.size(); i++) { cout << ans[i] << " "; } } cout << endl; } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); solve(); }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
t=int(input()) for kk in range(t): n=int(input()) l=list(map(int,input().split())) l1=list(filter(lambda x:x not in l,range(1,n*2+1))) l2=[] for i in l: j=0 flag=0 while j<len(l1): if l1[j]>i: l2.append(l1[j]) flag=1 del l1[j] break j+=1 if flag==0: break if flag==0: print(-1) else: for i in range(2*n): if i%2: print(l2.pop(0)) else: print(l.pop(0))
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
# import sys # sys.stdin = open("test.txt", 'r') for _ in range(int(input())): n = int(input()) b = list(map(int, input().split())) p = list(range(1, 2*n+1)) inb = set(b) a = {} for i, v in enumerate(b): if v == 2*n: print(-1) break c = [z for z in p[p.index(v)+1:] if z not in inb] if len(c) == 0: print(-1) break i += 1 a[2 * i-1] = v a[2*i] = c[0] p.remove(v) p.remove(c[0]) else: string = '' for i in range(1, 2*n+1): string += str(a[i]) + ' ' print(string)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> b(n + 5); vector<int> a(2 * n + 10); vector<pair<int, int>> p; map<int, int> mp; for (int i = 1; i <= n; i++) { cin >> b[i]; mp[b[i]]++; a[2 * i - 1] = b[i]; p.push_back({b[i], 2 * i}); } bool ok = true; for (int i = 0; i < p.size(); i++) { int st = p[i].first + 1; while (st <= 2 * n && mp[st] > 0) { st++; } if (st > 2 * n) { ok = false; break; } a[p[i].second] = st; mp[st]++; } if (!ok) { cout << -1 << "\n"; continue; } for (int i = 1; i <= n; i++) { if (a[2 * i - 1] > a[2 * i]) swap(a[2 * i - 1], a[2 * i]); } map<int, int> kek; for (int i = 1; i <= 2 * n; i++) { kek[a[i]]++; } for (int i = 1; i <= 2 * n; i++) { if (kek[i] != 1) { ok = false; break; } } if (!ok) { cout << -1 << "\n"; continue; } for (int i = 1; i <= 2 * n; i++) { cout << a[i] << " "; } cout << "\n"; } return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import copy for i in range(int(input())): n=int(input()) l=[int(j) for j in input().split()][:n] l1=list(set(list(range(1,2*n+1))).difference(set(l))) t=copy.deepcopy(l) l1.sort() m=-1 for k in range(n): h=-1 for j in range(n): if(l1[j]>t[k]): if l1[j] not in l: a=l.index(t[k]) l.insert(a+1,l1[j]) h=1 break if(h==-1): print("-1") m=1 break if(m==-1): for k in l: print(k,end=" ") print()
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; const int N = 205; int b[N], p[N], a[N]; int n; void check() { for (int i = 0; i < 2 * n; i += 2) { a[i] = b[i / 2]; bool flag = false; for (int j = b[i / 2] + 1; j <= 2 * n; ++j) { if (p[j] == 0) { p[j] = 1, a[i + 1] = j; flag = true; break; } } if (!flag) { printf("-1\n"); return; } } for (int i = 0; i < 2 * n; ++i) printf("%d ", a[i]); printf("\n"); } int main() { int t; cin >> t; while (t--) { scanf("%d", &n); memset(p, 0, sizeof(p)); for (int i = 0; i < n; ++i) scanf("%d", &b[i]), p[b[i]] = 1; check(); } return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import bisect t = int(input()) for i in range(t): n = int(input()) l = list(map(int,input().split())) l1 = [] l2 = [] c = 0 l3 = sorted(l) for i in range(min(l)+1,2*n+1): if i not in l: l1.append(i) if len(l1) == 0: print(-1) else: for i in l: if len(l1) == 0: c+=1 break w = bisect.bisect_left(l1,i) if w == len(l1): c+=1 break l2.append(i) l2.append(l1[w]) del l1[w] if c == 0: print(*l2) else: print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
from sys import stdin from collections import deque mod = 10**9 + 7 import sys import random # sys.setrecursionlimit(10**6) from queue import PriorityQueue # def rl(): # return [int(w) for w in stdin.readline().split()] from bisect import bisect_right from bisect import bisect_left from collections import defaultdict from math import sqrt,factorial,gcd,log2,inf,ceil # map(int,input().split()) # # l = list(map(int,input().split())) # from itertools import permutations import heapq # input = lambda: sys.stdin.readline().rstrip() input = lambda : sys.stdin.readline().rstrip() from sys import stdin, stdout from heapq import heapify, heappush, heappop from itertools import permutations from math import factorial as f def ncr(x, y): return f(x) // (f(y) * f(x - y)) t = int(input()) for _ in range(t): n = int(input()) l = list(map(int,input().split())) seti = set(i for i in range(1,2*n+1)) set1 = set(i for i in l) ans = [] flag = 0 ba = [i for i in range(1,2*n+1)] for i in range(n): z = l[i] if z not in seti: flag = 1 break else: seti.remove(z) ans.append(z) ka = len(ans) for j in ba: if j>z and j in seti and j not in set1: ans.append(j) seti.remove(j) break if len(ans) == ka: flag = 1 break # print(ans) if flag == 1: print(-1) else: print(*ans)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for ttt in range(int(input())): n=int(input()) arr=list(map(int,input().split())) if 2*n in arr or 1 not in arr: print(-1) continue res=[] for i in range(n): res.append(arr[i]) for j in range(arr[i]+1,2*n+1): if (j not in arr) and (j not in res): res.append(j) break if(len(res)==2*n): print(*res) else: print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 7; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while (t--) { int n; cin >> n; long long int a[n]; map<long long int, long long int> m; for (int i = 0; i < n; i++) { cin >> a[i]; m[a[i]] = 1; } vector<long long int> v; int yo = 0; for (int i = 0; i < n; i++) { if (a[i] + 1 > 2 * n) { yo = 1; break; } if (!m[a[i] + 1]) { v.push_back(a[i]); v.push_back(a[i] + 1); m[a[i] + 1] = 1; } else { long long int z = -1; for (int j = a[i] + 1; j <= 2 * n; j++) { if (!m[j]) { z = j; break; } } if (z != -1) { v.push_back(a[i]); v.push_back(z); m[z] = 1; } else yo = 1; } if (yo == 1) break; } if (yo == 1) cout << "-1" << endl; else { for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << endl; } } return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
##############--->>>>> Deepcoder Amit Kumar Bhuyan <<<<<---############## """ Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away. """ from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def msi(): return map(str,input().strip().split(" ")) def li(): return list(mi()) def dmain(): sys.setrecursionlimit(1000000) threading.stack_size(1024000) thread = threading.Thread(target=main) thread.start() #from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace #from math import log,sqrt,factorial,cos,tan,sin,radians #from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right #from decimal import * #import threading #from itertools import permutations #Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy import sys input = sys.stdin.readline scanner = lambda: int(input()) string = lambda: input().rstrip() get_list = lambda: list(read()) read = lambda: map(int, input().split()) get_float = lambda: map(float, input().split()) # from bisect import bisect_left as lower_bound; # from bisect import bisect_right as upper_bound; # from math import ceil, factorial; def ceil(x): if x != int(x): x = int(x) + 1 return x def factorial(x, m): val = 1 while x>0: val = (val * x) % m x -= 1 return val def fact(x): val = 1 while x > 0: val *= x x -= 1 return val # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; ## gcd function def gcd(a,b): if b == 0: return a; return gcd(b, a % b); ## lcm function def lcm(a, b): return (a * b) // math.gcd(a, b) def is_integer(n): return math.ceil(n) == math.floor(n) ## nCr function efficient using Binomial Cofficient def nCr(n, k): if k > n: return 0 if(k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## upper bound function code -- such that e in a[:i] e < x; ## prime factorization def primefs(n): ## if n == 1 ## calculating primes primes = {} while(n%2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n//2 for i in range(3, int(n**0.5)+2, 2): while(n%i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n//i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): if y == 0: return 1 res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## DISJOINT SET UNINON FUNCTIONS def swap(a,b): temp = a a = b b = temp return a,b; # find function with path compression included (recursive) # def find(x, link): # if link[x] == x: # return x # link[x] = find(link[x], link); # return link[x]; # find function with path compression (ITERATIVE) def find(x, link): p = x; while( p != link[p]): p = link[p]; while( x != p): nex = link[x]; link[x] = p; x = nex; return p; # the union function which makes union(x,y) # of two nodes x and y def union(x, y, link, size): x = find(x, link) y = find(y, link) if size[x] < size[y]: x,y = swap(x,y) if x != y: size[x] += size[y] link[y] = x ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n+1)] prime[0], prime[1] = False, False p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime # Euler's Toitent Function phi def phi(n) : result = n p = 2 while(p * p<= n) : if (n % p == 0) : while (n % p == 0) : n = n // p result = result * (1.0 - (1.0 / (float) (p))) p = p + 1 if (n > 1) : result = result * (1.0 - (1.0 / (float)(n))) return (int)(result) def is_prime(n): if n == 0: return False if n == 1: return True for i in range(2, int(n ** (1 / 2)) + 1): if not n % i: return False return True def next_prime(n, primes): while primes[n] != True: n += 1 return n #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e5 + 5) def spf_sieve(): spf[1] = 1; for i in range(2, MAXN): spf[i] = i; for i in range(4, MAXN, 2): spf[i] = 2; for i in range(3, ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i*i, MAXN, i): if spf[j] == j: spf[j] = i; ## function for storing smallest prime factors (spf) in the array ################## un-comment below 2 lines when using factorization ################# spf = [0 for i in range(MAXN)] # spf_sieve(); def factoriazation(x): res = [] for i in range(2, int(x ** 0.5) + 1): while x % i == 0: res.append(i) x //= i if x != 1: res.append(x) return res ## this function is useful for multiple queries only, o/w use ## primefs function above. complexity O(log n) def factors(n): res = [] for i in range(1, int(n ** 0.5) + 1): if n % i == 0: res.append(i) res.append(n // i) return list(set(res)) ## taking integer array input def int_array(): return list(map(int, input().strip().split())); def float_array(): return list(map(float, input().strip().split())); ## taking string array input def str_array(): return input().strip().split(); def binary_search(low, high, w, h, n): while low < high: mid = low + (high - low) // 2 # print(low, mid, high) if check(mid, w, h, n): low = mid + 1 else: high = mid return low ## for checking any conditions def check(val, pair): summ = 0 for x in pair: if x[1] > val: summ += x[0] return summ > val ## for sorting according to second position def sortSecond(val): return val[1] #defining a couple constants MOD = int(1e9)+7; CMOD = 998244353; INF = float('inf'); NINF = -float('inf'); alphs = "abcdefghijklmnopqrstuvwxyz" ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### from itertools import permutations import math import bisect as bis import random import sys import collections as collect import functools as fnt from decimal import Decimal # from sys import stdout # import numpy as np """ _______________ rough work here _______________ n piranhas with sizes a1, a2, .... an scientist of berland state univ want to find if there is dominant piranha the piranha is dominant if it can eat all the other piranhas in the aquarium piranha can eat only one of the adjacent piranhas during one move piranha can do as many moves as it needs piranha i can eat i - 1 """ def solve(): n = scanner() b = get_list() a = [] vis = [0] * (2 * n) mp = {} for x in b: mp[x] = 1 if x > 2 * n: print(-1) return vis[x - 1] = 1 for x in b: a.append(x) mp[x] = 1 for i in range(1, 201): if i > x and mp.get(i) == None: a.append(i) if i > 2 * n: print(-1) return vis[i - 1] = 1 mp[i] = 1 break if sum(vis) == 2 * n: print(*a) else: print(-1) # region fastio # template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": #read() # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") t = scanner() for i in range(t): solve() #dmain() # Comment Read() # fin_time = datetime.now() # print("Execution time (for loop): ", (fin_time-init_time))
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
# from collections import deque import sys input = lambda: sys.stdin.readline().strip() for i in range(int(input())): n = int(input()) b = list(map(int,input().split())) q = [i+1 for i in range(2*n)] used = set(b) j = 0 a = [0]*2*n f = True for i in range(n): a[2*i]=b[i] for i in range(n): for j in q[b[i]-1:]: if j not in used: used.add(j) a[2*i+1]=j break if a[2*i+1]==0: f = False break if not f: print(-1) continue else: print(' '.join(map(str,a)))
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
# /////////////////////////////////////////////////////////////////////////// # //////////////////// LEGEND //////////////////////// # /////////////////////////////////////////////////////////////////////////// import sys,os,io from sys import stdin import math from collections import defaultdict from heapq import heappush, heappop, heapify from bisect import bisect_left , bisect_right from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") alphabets = list('abcdefghijklmnopqrstuvwxyz') #for deep recursion__________________________________________- from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den,p - 2, p)) % p def primeFactors(n): l = [] while n % 2 == 0: l.append(2) n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: l.append(int(i)) n = n / i if n > 2: l.append(n) # c = dict(Counter(l)) return list(set(l)) # return c def power(x, y, p) : res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res #____________________GetPrimeFactors in log(n)________________________________________ def sieveForSmallestPrimeFactor(): MAXN = 100001 spf = [0 for i in range(MAXN)] spf[1] = 1 for i in range(2, MAXN): spf[i] = i for i in range(4, MAXN, 2): spf[i] = 2 for i in range(3, math.ceil(math.sqrt(MAXN))): if (spf[i] == i): for j in range(i * i, MAXN, i): if (spf[j] == j): spf[j] = i return spf def getPrimeFactorizationLOGN(x): spf = sieveForSmallestPrimeFactor() ret = list() while (x != 1): ret.append(spf[x]) x = x // spf[x] return ret #____________________________________________________________ def SieveOfEratosthenes(n): #time complexity = nlog(log(n)) prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime def si(): return input() def divideCeil(n,x): if (n%x==0): return n//x return n//x+1 def ii(): return int(input()) def li(): return list(map(int,input().split())) # /////////////////////////////////////////////////////////////////////////// # //////////////////// DO NOT TOUCH BEFORE THIS LINE //////////////////////// # /////////////////////////////////////////////////////////////////////////// if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w") else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def solve(): n = ii() b = li() d = defaultdict(lambda:0) for i in b: d[i]=1 noth = [] for i in range(1,2*n+1): if d[i]==0: noth.append(i) ans = [] s = SortedList(noth) # b.sort() for i in range(n): ptr = s.bisect_left(b[i]) if ptr==len(s) or s[ptr]<b[i]: print(-1) return ans.append(b[i]) ans.append(s[ptr]) s.remove(s[ptr]) print(*ans) t = 1 t = ii() for _ in range(t): solve()
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(bf.readLine()); while(t-->0) { int n=Integer.parseInt(bf.readLine()); String s[]=bf.readLine().split(" "); ArrayList<Integer> al=new ArrayList<>(); for(int i=0;i<n;i++) { al.add(Integer.parseInt(s[i])); } int range=2*n; ArrayList<Integer> al2=new ArrayList<>(); boolean sangam=true; for(int i=0;i<n;i++) { int z=al.get(i); al2.add(z); z++; while(true) { if(al.contains(z) || al2.contains(z)) { z++; } else { if(z<=range) { al2.add(z); break; } else { sangam=false; break; } } } if(sangam==false) { break; } } // System.out.println(al); // System.out.println(al2); if(sangam) { for(int i=0;i<al2.size();i++) { System.out.print(al2.get(i)+" "); } System.out.println(); } else { System.out.println(-1); } } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; int mark[2005]; int main() { long long n, m, i, j, t, x, y, w, k, a, b; cin >> t; while (t--) { cin >> n; vector<pair<int, int> > v; memset(mark, 0, sizeof mark); for (i = 0; i < n; i++) { cin >> x; v.push_back({x, -1}); mark[x] = 1; } set<int> s; for (i = 1; i <= 2 * n; i++) { if (mark[i] == 0) { s.insert(i); } } int flag = 1; for (i = 0; i < n; i++) { x = v[i].first; int ans = -1; for (auto xx : s) { if (xx > x) { ans = xx; break; } } if (ans == -1) { flag = -1; break; } else { v[i].second = ans; s.erase(ans); } } if (flag == -1) { cout << (-1) << "\n"; } else { for (i = 0; i < n; i++) { cout << min(v[i].first, v[i].second) << " " << max(v[i].first, v[i].second) << " "; } cout << "\n"; } } return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for _ in range(int(input())): n=int(input()) b=[int(x) for x in input().split()] a=[] for i in range(n): a.append(b[i]) k=b[i] while k in a or k in b:k+=1 if k>2*n:print(-1);break a.append(k) else:print(*a)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
I=input for _ in[0]*int(I()): I();b=*map(int,I().split()),;s={*range(2*len(b)+1)}-{*b};a=[] try: for x in b:a+=x,min(s-{*range(x)});s-={*a} except:a=-1, print(*a)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) dic={};ans=[];boo=False for i in a: dic[i]=0 for i in a: ans.append(i) temp=i+1 while(True): if(temp>2*n): boo=True break if(temp not in dic.keys()): dic[temp]=0 ans.append(temp) break temp+=1 if(boo): break if(boo): print(-1) else: print(*ans)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.*; import java.util.*; public class test { static int m[]; public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); int t=sc.nextInt(); while (t-->0){ StringBuilder sb=new StringBuilder(); int N=sc.nextInt(); int sum[]=new int[N]; boolean con[]=new boolean[2*N + 1]; TreeSet<Integer> set=new TreeSet<>(); for (int i=0;i<N;i++){ sum[i]=sc.nextInt(); con[sum[i]]=true; } for (int i=1;i<=2*N;i++){ if (!con[i])set.add(i); } boolean z=false; for (int j=0;j<N;j++) { Integer x=set.ceiling(sum[j]); if (x==null){ z=true; break; } sb.append(sum[j]+" "+x+" "); set.remove(x); } if (z) System.out.println(-1); else System.out.println(sb); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.*; public class Sol{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[] b=new int[n+1]; int[] bb=new int[n]; int le=2*n; Set<Integer> h=new HashSet<>(); int min=0; ArrayList<Integer> al= new ArrayList<>(); ArrayList<Integer> alb= new ArrayList<>(); ArrayList<Integer> aa= new ArrayList<>(); Map<Integer,Integer> mp=new HashMap<>(); for(int i=1;i<=n;i++){ b[i]=sc.nextInt(); bb[i-1]=b[i]; alb.add(b[i]); h.add(b[i]); if(min<b[i]){ min=b[i]; } } boolean ok=true; for(int i=1;i<=n ;i++){ ok=false; for(int jjj=0;jjj<=le;jjj++){ int j=b[i]+jjj; if(!alb.contains(j)&& ok!=true && j<=le){ alb.add(j); aa.add(j); ok=true; } } } /* int p=1; Arrays.sort(bb); Collections.sort(aa); int[] cc=new int[le+1]; for(int i=1;i<=le;i+=2){ mp.put( bb[i-p],aa.get(i-p)); p++; } */ if( h.size()!=n|| min>=n*2 ||aa.size()!=n){ System.out.println("-1"); } else{ for(int i=1;i<=n;i++){ System.out.print( b[i]+" "+aa.get(i-1)+" "); } System.out.println(); } } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; const int maxn = 3e5 + 20; const int inf = 0x3f3f3f3f; const int modd = 1e9 + 7; inline int read() { int x = 0, f = 1; char c = getchar(); while (c != '-' && (c < '0' || c > '9')) c = getchar(); if (c == '-') f = -1, c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return f * x; } template <class T> inline void sc(T &x) { char c; x = 0; while ((c = getchar()) < '0') ; while (c >= '0' && c <= '9') x = x * 10 + (c - 48), c = getchar(); } inline long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } inline long long exgcd(long long a, long long b, long long &x, long long &y) { long long d; (b == 0 ? (x = 1, y = 0, d = a) : (d = exgcd(b, a % b, y, x), y -= a / b * x)); return d; } inline long long qpow(long long a, long long n) { long long sum = 1; while (n) { if (n & 1) sum = sum * a % modd; a = a * a % modd; n >>= 1; } return sum; } inline long long qmul(long long a, long long n) { long long sum = 0; while (n) { if (n & 1) sum = (sum + a) % modd; a = (a + a) % modd; n >>= 1; } return sum; } inline long long inv(long long a) { return qpow(a, modd - 2); } struct Coke { int v, id; } a[maxn]; bool cmp1(Coke c, Coke d) { return c.v < d.v; } bool cmp2(Coke c, Coke d) { return c.id < d.id; } int vis[205]; int ans[maxn]; vector<int> vec; int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); for (int i = 1; i <= 2 * n; i++) vis[i] = 0; vec.clear(); for (int i = 1; i <= n; i++) scanf("%d", &a[i].v), a[i].id = i, ans[i * 2 - 1] = a[i].v; sort(a + 1, a + 1 + n, cmp1); for (int i = 1; i <= n; i++) vis[a[i].v] = a[i].id; int now = 0, flag = 1; for (int i = 1; i <= 2 * n; i++) if (!vis[i]) vec.push_back(i); sort(a + 1, a + 1 + n, cmp2); for (int i = 1; i <= n; i++) { auto it = lower_bound(vec.begin(), vec.end(), a[i].v); if (it == vec.end()) { flag = 0; break; } ans[a[i].id * 2] = *it; vec.erase(it); } if (!flag) { printf("-1\n"); continue; } for (int i = 1; i <= 2 * n; i++) printf("%d%c", ans[i], " \n"[i == 2 * n]); } }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T-- > 0) { int a = sc.nextInt(); int[] x = new int[a + 1]; int min = 1; int[] y = new int[a * 2 + 1]; boolean bo = true; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 1; i <= a; i++) { x[i] = sc.nextInt(); map.put(x[i], 1); } for (int i = 1; i <= a; i++) { int k = -1; for (int j = x[i] + 1; j <= 2 * a; j++) { if (!map.containsKey(j)) { map.put(j, 1); k = j; break; } } if (k == -1) { bo = false; System.out.println(-1); break; } else { y[i * 2] = k; y[i * 2 - 1] = x[i]; } } if (bo) { for (int i = 1; i < 2 * a; i++) { System.out.print(y[i] + " "); } System.out.println(y[2 * a]); } } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.Scanner; public class Test2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int test = scanner.nextInt(); for(int t = 0; t<test; ++t){ int n = scanner.nextInt(); int[] sc = new int[(2 * n )+1]; int[] op = new int[(2 * n )+1]; int[] a = new int [n+1]; for(int i=1; i<=n; ++i){ a[i] = scanner.nextInt(); sc[a[i]] = 1; op[2*i-1] = a[i]; } boolean found = false; for(int i=1; i<=n; ++i){ found = false; for(int j = a[i]+1; j<=(2*n) ; ++j){ if(sc[j]==0){ op[2*i] = j; sc[j] = 1; found = true; break; } } if(!found){ break; } } if(!found){ System.out.println("-1"); } else{ for(int i=1; i<=(2*n); ++i){ System.out.print(op[i] + " "); } System.out.println(); } } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.Scanner; import java.util.Stack; import java.util.Arrays; public class C{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int t = in.nextInt(); StringBuilder res = new StringBuilder(); o1: for(int j = 0;j<t;++j){ StringBuilder resLocal = new StringBuilder(); int n = in.nextInt(); int[] b = new int[n]; for(int i = 0;i<n;++i) b[i] = in.nextInt(); int[] a = new int[2*n]; int[] flag = new int[2*n+1]; for(int i = 0;i<n;++i){ if(flag[b[i]] == 1){ res.append("-1\n"); continue o1; } a[2*i] = b[i]; flag[b[i]] = 1; } // System.out.println(Arrays.toString(a) + "\n"); for(int i = 0;i<2*n;++i){ if(a[i] == 0) { for(int k = a[i-1];k<=2*n;++k){ if(flag[k] == 1) continue; // System.out.println(flag[k] + " " + k + " " + i); flag[k] = 1; a[i] = k; break; } } if(a[i] == 0){ res.append("-1\n"); continue o1; } resLocal.append(a[i] + " "); } res.append(resLocal.append("\n").toString()); } System.out.println(res); } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.*; import java.util.*; public class Main { static BufferedReader br; static StringTokenizer st; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static class HS<T> extends HashSet<T> {}; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); int t = nxtInt(); while(t-- > 0) { st = new StringTokenizer(br.readLine()); int n = nxtInt(); int[] a = new int[n*2]; HS<Integer> mrk = new HS<>(); st = new StringTokenizer(br.readLine()); for(int i=0; i<n; i++) { a[i*2] = nxtInt(); mrk.add(a[i*2]); } boolean flg = true; StringBuilder ans = new StringBuilder(); for(int i=1; i<a.length; i+=2) { int num = a[i-1]; while(num<n*2+1 && mrk.contains(num)) num++; if(num > n*2) { flg = false; break; } a[i] = num; mrk.add(num); ans.append(a[i-1] + " " + a[i] + " "); } pr.println(flg? ans: -1); } pr.flush(); pr.close(); } static int nxtInt(){ return Integer.parseInt(nxt()); } static long nxtLong(){ return Long.parseLong(nxt()); } static double nxtDoub(){ return Double.parseDouble(nxt()); } static String nxt(){ return st.nextToken(); } static String nxtLn() throws IOException{ return br.readLine(); } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; int main() { int i, j, k, n, t, c; cin >> t; for (; t > 0; t--) { c = 1; cin >> n; int a[2 * n]; bool x[2 * n + 1]; memset(x, 0, sizeof(x)); j = 1; for (i = 0; i < n; i++) { cin >> k; a[2 * i] = k; x[k] = 1; } for (i = 0; i < n; i++) { j = a[2 * i]; j++; for (; x[j] == 1 && j <= 2 * n; j++) ; if (j <= 2 * n) { a[2 * i + 1] = j; x[j] = 1; } else break; } if (i == n) for (i = 0; i < n; i++) cout << a[2 * i] << " " << a[2 * i + 1] << " "; else cout << -1; cout << endl; } }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
from collections import Counter as C,defaultdict as D,deque as Q from operator import itemgetter as I from itertools import product as P from bisect import bisect_left as BL,bisect_right as BR from heapq import heappush as HPUSH,heappop as HPOP from math import floor as MF,ceil as MC, gcd as MG,factorial as F,sqrt as SQRT, inf as INFINITY,log as LOG from sys import stdin, stdout INPUT=stdin.readline PRINT=stdout.write def player1(): print("") def player2(): print("") def isPrime(n): for i in range(2,MC(SQRT(n))+1): if n%i==0: return False return True def factors(x): ans=[] for i in range(1,MC(SQRT(x))+1): if x%i==0: ans.append(i) if x%(x//i)==0: ans.append(x//i) return ans def main(): for _ in range(int(INPUT())): n=int(INPUT());b=list(map(int,INPUT().split( ))) c=C(b) if c[2*n]: PRINT("%d "%(-1)) continue a=[i for i in range(1,2*n+1) if c[i]==0] ans=[];l=len(a) for v in b: index=BR(a,v) if index==l: ans=-1 break ans.append(a[index]) a.remove(a[index]) l-=1 else: for x,y in zip(b,ans): PRINT("%d %d "%(x,y)) continue PRINT("%d "%(-1)) main()
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.Scanner; public class RestoringPermutation { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-->0){ int n = sc.nextInt(); int arr[] = new int[n]; int covered[] = new int[2*n+1]; for(int i=0;i<n;i++){ int num = sc.nextInt(); arr[i] = num; covered[num] = 1; } int ans[] = new int[n]; int count = 0; for(int i=0;i<n;i++){ int num = arr[i]; for(int j=num+1;j<=2*n;j++){ if(covered[j] == 0){ ans[i] = j; covered[j] = 1; count++; break; } } } if(count == n){ for(int i=0;i<n;i++){ System.out.print(arr[i]+" "+ans[i]+" "); } System.out.println(); } else System.out.println("-1"); } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for i in range(int(input())): n = int(input()) b_array = list(map(int, input().split())) a_array = sorted(list(set(list(map(int, range(1, 2*n+1)))) - set(b_array))) sorted_array = sorted(list(map(list, list(zip(b_array, list(map(int, range(n)))))))) #print(sorted_array) final_array = [0]*(2*n) state = True for j in range(2*n): if j % 2 == 0: final_array[j] = b_array[int(j/2)] else: final_array[j] = 0 #print(final_array) #print(a_array) #print(sorted_array) for j in range(n): if sorted_array[j][0] < a_array[j]: final_array[2*sorted_array[j][1]+1] = a_array[j] else: print(-1) state = False break if state == True: for j in range(n-1): while True: k = 2 p = -1 while ((j*2)+1+k < 2*n): if ((final_array[j*2] < final_array[(j*2)+1+k]) and (final_array[(j*2)+k] < final_array[(j*2)+1]) and (final_array[(j*2)+1] > final_array[(j*2)+1+k])): p = (j*2)+1+k k+=2 if p != -1: final_array[(j*2)+1], final_array[p] = final_array[p], final_array[(j*2)+1] else: break print(' '.join(list(map(str, final_array))))
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for _ in range(int(input())): n = int(input()) seq = list(map(int, input().split())) if(len(set(seq))) != n or max(seq) > 2 * n - 1: print(-1) continue myst = set(range(1, 2 * n + 1)) - set(seq) myst = list(sorted(myst)) #fnd = list(sorted(map(lambda tp: (tp[1], tp[0]), enumerate(seq)))) ans = [] fl = True for x in seq: upbnd = 0 while upbnd < len(myst) and myst[upbnd] < x: upbnd += 1 if upbnd == len(myst): fl = False break ans.append(x) ans.append(myst[upbnd]) myst.pop(upbnd) if not fl: print(-1) else: print(*ans)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; int n; int in; bool ispossible; bool ischanged; while (t--) { ispossible = true; map<int, bool> isused; vector<int> a; vector<int> b; cin >> n; for (int i = 0; i < n; i++) { cin >> in; a.push_back(in); isused[in] = true; } for (int i = 0; i < n; i++) { ischanged = false; for (int j = a[i] + 1; j <= 2 * n; j++) { if (!isused[j]) { b.push_back(j); isused[j] = true; ischanged = true; break; } } if (!ischanged) { ispossible = false; break; } } if (!ispossible) { cout << -1 << endl; } else { for (int i = 0; i < n; i++) { cout << a[i] << ' '; cout << b[i] << ' '; } cout << endl; } } }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for _ in range(int(input())): n=int(input()) L=[int(x) for x in input().strip().split(" ")] exist=set(L) todo=set() for i in range(1,2*n+1): if i not in exist: todo.add(i) res=[] flag=True for x in L: for e in range(x+1,2*n+1): if e in todo: res.append(x) res.append(e) todo.remove(e) break else: flag=False break if not flag: print(-1) else: for x in res: print(x,end=" ") print()
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 500; const long long mod = 1e9 + 7; const long long cmod = 998244353; const long long inf = 1LL << 61; const int M = 1e6 + 500; const long long int ths = 1LL << 40; const int NN = 5e3 + 6; void solve() { long long int n; cin >> n; long long int b[n + 1], a[2 * n + 1]; set<long long int> s; for (int i = 1; i <= 2 * n; i++) s.insert(i); for (int i = 1; i <= n; i++) { cin >> b[i]; s.erase(b[i]); } vector<long long int> v; for (auto it : s) v.push_back(it); long long int idx = 1; bool ok = 1; for (int i = 1; i <= n; i++) { a[idx] = b[i]; idx++; long long int x = *s.upper_bound(b[i]); if (s.count(x) == 0) { ok = 0; break; } s.erase(x); a[idx] = x; idx++; } if (!ok) { cout << -1; } else { for (int i = 1; i <= 2 * n; i++) cout << a[i] << ' '; } cout << '\n'; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 1; cin >> t; while (t--) { solve(); } return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#Ashish Sagar import math q=int(input()) #q=1 for _ in range(q): n=int(input()) b=list(map(int,input().split())) ans=[0]*(2*n) if min(b)!=1 or max(b)==2*n: print(-1) else: l=[1]*(2*n+1) for i in range(n): l[b[i]]=0 #print(l) '''aa=[] for i in range(1,2*n+1): if l[i]==1: aa.append(i)''' #print(aa) k=0 for i in range(2*n): if i%2==0: ans[i]=b[k] k+=1 l[0]=0 #print(l) for i in range(0,2*n,2): for j in range(ans[i]+1,2*n+1): if l[j]==1: ans[i+1]=j l[j]=0 break if ans.count(0)!=0: print(-1) else: print(*ans)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.ArrayList; import java.util.Collections; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Random; import java.io.PrintWriter; /* Solution Created: 19:12:15 23/02/2020 Custom Competitive programming helper. */ public class Main { public static void solve(Reader in, Writer out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int[] b = in.na(n); int[] a = new int[2*n]; boolean can = true; for(int i = 0; i<n; i++) a[i*2] = b[i]; boolean[] used = new boolean[2*n+1]; for(int i = 0; i<n; i++) used[b[i]] = true; int[] left = new int[n]; int idx = 0; for(int i = 1; i<=2*n; i++) if(!used[i]) left[idx++] = i; for(int i = 0; i<n; i++) { idx = i*2+1; int last = a[idx-1]; boolean found = false; for(int j = 0; j<n&&(!found); j++) { if(left[j]==-1) continue; if(left[j]>last) { found = true; a[idx] = left[j]; left[j] = -1; } } if(!found) can = false; } if(can) { for(int i = 0; i<2*n; i++) out.print(a[i]+" "); out.println(); }else out.println(-1); } } public static void main(String[] args) { Reader in = new Reader(); Writer out = new Writer(); solve(in, out); out.exit(); } static class Graph { private ArrayList<Integer> con[]; private boolean[] visited; public Graph(int n) { con = new ArrayList[n]; for (int i = 0; i < n; ++i) con[i] = new ArrayList(); visited = new boolean[n]; } public void reset() { Arrays.fill(visited, false); } public void addEdge(int v, int w) { con[v].add(w); } public void dfs(int cur) { visited[cur] = true; for (Integer v : con[cur]) { if (!visited[v]) { dfs(v); } } } public void bfs(int cur) { Queue<Integer> q = new LinkedList<>(); q.add(cur); visited[cur] = true; while (!q.isEmpty()) { cur = q.poll(); for (Integer v : con[cur]) { if (!visited[v]) { visited[v] = true; q.add(v); } } } } } static class Reader { static BufferedReader br; static StringTokenizer st; private int charIdx = 0; private String s; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char nextChar() { if (s == null || charIdx >= s.length()) { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } s = st.nextToken(); charIdx = 0; } return s.charAt(charIdx++); } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] nS(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Integer.parseInt(st.nextToken()); } public double nextDouble() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Double.parseDouble(st.nextToken()); } public Long nextLong() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Long.parseLong(st.nextToken()); } public String next() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return st.nextToken(); } public static void readLine() { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } } static class Solution { public static void solve(Reader in, Writer out) { } } static class Sort { static Random random = new Random(); public static void sortArray(int[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(long[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(String[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(char[] s) { shuffle(s); Arrays.sort(s); } private static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(String[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); String t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } } static class Util{ static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static int upperBound(long[] a, long v) { int l=0, h=a.length-1, ans = -1; while(l<h) { int mid = (l+h)/2; if(a[mid]<=v) { ans = mid; l = mid+1; }else h = mid-1; } return ans; } public static int lowerBound(long[] a, long v) { int l=0, h=a.length-1, ans = -1; while(l<h) { int mid = (l+h)/2; if(v<=a[mid]) { ans = mid; h = mid-1; }else l = mid-1; } return ans; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } public static long modAdd(long a, long b, long mod) { return (a%mod+b%mod)%mod; } public static long modMul(long a, long b, long mod) { return ((a%mod)*(b%mod))%mod; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { int n=ni(); TreeSet<Integer> set = new TreeSet<Integer>(); for(int i=1;i<=2*n;i++) set.add(i); int[]B=nai(n); for(int i=0;i<n;i++) set.remove(B[i]); // System.err.println(set); int[]A=new int[2*n]; for(int i=0;i<2*n;i++) { if(i%2==0) A[i]=B[i/2]; else { if(set.ceiling(A[i-1])==null) { pn("-1"); return; } A[i]=set.ceiling(A[i-1]); set.remove(set.ceiling(A[i-1])); } } for(int i=0;i<A.length;i++) p(A[i]+" "); pn(""); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; t=ni(); while(t-->0) {process();} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.*; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); int tests = s.nextInt(); while(tests--!=0){ int n = s.nextInt(); int freq[] = new int[2*n +1]; int arr[] = new int[2*n +1]; boolean flag = false; TreeSet<Integer>ts = new TreeSet<>(); for(int i=0;i<2*n;i+=2){ arr[i]= s.nextInt(); freq[arr[i]]++; } for(int i=1;i<=2*n;i++){ if(freq[i]==0)ts.add(i); } for(int i=1;i<=2*n;i+=2){ int x = arr[i-1]; if(ts.ceiling(x)==null){ flag=true; break; } else{ arr[i]=ts.ceiling(x); ts.remove(arr[i]); } } if(flag) System.out.println(-1); else{ for(int i=0;i<2*n;i++){ System.out.print(arr[i]+" "); } System.out.println(); } } } } class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
//package Practise; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeSet; public class RestoringPermutation { public static void main(String args[]) { FastScanner fs=new FastScanner(); int t=fs.nextInt(); for(int t1=0;t1<t;t1++) { int n=fs.nextInt(); int []arr=new int[n]; boolean []check=new boolean[2*n+1]; for(int i=0;i<n;i++) { arr[i]=fs.nextInt(); check[arr[i]]=true; } TreeSet<Integer> set=new TreeSet<>(); for(int i=1;i<check.length;i++) { if(!check[i]) set.add(i); } List<Integer> list=new ArrayList<>();boolean flag=false; for(int i=0;i<arr.length;i++) { list.add(arr[i]); Integer val=set.higher(arr[i]); flag=val==null?true:false; if(flag) break; list.add(val); set.remove((Object)val); } if(flag) System.out.println("-1"); else { for(int val:list) System.out.print(val+" "); System.out.println(); } } } private static int[] readArray(int n) { // TODO Auto-generated method stub return null; } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
test=int(input()) for i in range(test): n = int(input()) b = list(map(int, input().split())) a = [0 for i in range(n+n)] l = [0 for i in range(n+n+1)] for i in range(n): a[2*i] = b[i] l[b[i]] = 1 ans = 1 for i in range(n): bool = 0 for j in range(b[i]+1, n+n+1): if l[j] == 1: continue a[2*i+1] = j l[j] = 1 bool = 1; break if bool == 0: ans = 0 break if ans == 0: print(-1) else: for i in range(n+n): print(a[i], end = ' ') print()
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; void solve() { int64_t n; cin >> n; int64_t b[n + 1], a[2 * n + 1]; map<int64_t, int64_t> f; while (1 > 2) ; while (1 > 2) ; while (1 > 2) ; bool fl = 0; for (int64_t i = 1; i <= n; ++i) { cin >> b[i]; while (1 > 2) ; while (1 > 2) ; while (1 > 2) ; if (f[b[i]] == 1) { cout << -1 << '\n'; fl = 1; break; } else f[b[i]] = 1; } if (fl == 1) { return; } while (1 > 2) ; while (1 > 2) ; while (1 > 2) ; for (int64_t i = 1; i <= n; ++i) { int64_t x; for (x = b[i]; x <= 2 * n + 1; ++x) if (f[x] == 0) break; if (x == 2 * n + 1) { cout << -1 << endl; fl = 1; while (1 > 2) ; while (1 > 2) ; while (1 > 2) ; break; } f[x] = 1; a[2 * i - 1] = min(x, b[i]); while (1 > 2) ; while (1 > 2) ; while (1 > 2) ; a[2 * i] = max(x, b[i]); } if (fl == 1) { return; } for (int64_t i = 1; i <= 2 * n; ++i) { cout << a[i] << ' '; } while (1 > 2) ; while (1 > 2) ; while (1 > 2) ; cout << endl; } int32_t main() { int64_t q; cin >> q; while (q--) { while (1 > 2) ; while (1 > 2) ; while (1 > 2) ; solve(); while (1 > 2) ; while (1 > 2) ; while (1 > 2) ; } }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import sys from collections import defaultdict def make(b): n=len(b) ans=[-1 for _ in range(2*n)] vis=defaultdict(int) for i in range(0,2*n,2): ans[i]=b[i//2] vis[b[i//2]]=1 for i in range(1,2*n,2): for j in range(ans[i-1]+1,2*n+1): if vis[j]==0: ans[i]=j vis[j]=1 break if ans[i]==-1: return False return ans t=int(sys.stdin.readline()) for _ in range(t): n=int(sys.stdin.readline()) b=list(map(int,sys.stdin.readline().split())) a=make(b) if a: print(*a) else: print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.*; import java.util.*; public class RestoringPermutation{ static Scanner sc = new Scanner(System.in); static void restorePermutation(){ int n = sc.nextInt(); boolean map[] = new boolean[(2*n + 1)]; int input[] = new int[n]; int output[] = new int[n]; map[0] = true; for(int i=0;i<n;i++){ int index = sc.nextInt(); input[i] = index; map[index] = true; } for(int i=0;i<n;i++) { int curr = input[i]; map[0] = false; for(int j=curr+1;j<=2*n;j++) { if(!map[j]) { output[i] = j; map[j] = true; map[0] = true; break; } } if(!map[0]) break; } if(map[0]) { for(int i=0;i<n;i++) System.out.print(input[i] + " " + output[i] + " "); } else System.out.print(-1); System.out.println(); } public static void main(String[] args) { int t = sc.nextInt(); while(t-- > 0) restorePermutation(); } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter; import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Array;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;import java.security.AccessControlException;import java.util.ArrayList; import java.util.Arrays;import java.util.Collection;import java.util.Comparator; import java.util.List;import java.util.Map;import java.util.Objects;import java.util.TreeMap; import java.util.TreeSet;import java.util.function.Function;import java.util.stream.Collectors; import java.util.stream.IntStream;import java.util.stream.LongStream;import java.util.stream.Stream; public class _p001315C {static public void main(final String[] args) throws IOException {p001315C._main(args);} static class p001315C extends Solver{public p001315C(){}@Override public void solve()throws IOException{int n=sc.nextInt();sc.nextLine();int[]b=Arrays.stream(sc.nextLine().trim().split("\\s+")).filter($s2 ->!$s2.isEmpty()).mapToInt(Integer::parseInt).toArray();TreeSet<Integer>seta=new TreeSet<>();seta.addAll(IntStream.rangeClosed(1,2*n).boxed().collect(Collectors.toList())); seta.removeAll(Datas.list(b));ArrayList<Integer>res=new ArrayList<>();for(int itb:b){Integer ita=seta.ceiling(itb);if(ita!=null){res.add(itb);res.add(ita);seta.remove(ita);} else{res.clear();break;}}if(res.isEmpty()){pw.println(-1);}else{pw.println(Datas.join(res)); }}static public void _main(String[]args)throws IOException{new p001315C().run();} }static class Datas{static class Pair<K,V>{private K k;private V v;public Pair(final K t,final V u){this.k=t;this.v=u;}public K getKey(){return k;}public V getValue() {return v;}}final static String SPACE=" ";public static TreeMap<Integer,Integer> mapc(final int[]a){return IntStream.range(0,a.length).collect(()->new TreeMap<Integer, Integer>(),(res,i)->{res.put(a[i],res.getOrDefault(a[i],0)+1);},Map::putAll);}public static TreeMap<Long,Integer>mapc(final long[]a){return IntStream.range(0,a.length).collect( ()->new TreeMap<Long,Integer>(),(res,i)->{res.put(a[i],res.getOrDefault(a[i],0)+ 1);},Map::putAll);}public static<T>TreeMap<T,Integer>mapc(final T[]a,Comparator<T> cmp){return IntStream.range(0,a.length).collect(cmp!=null?()->new TreeMap<T,Integer>(cmp) :()->new TreeMap<T,Integer>(),(res,i)->{res.put(a[i],res.getOrDefault(a[i],0)+1); },Map::putAll);}public static<T>TreeMap<T,Integer>mapc(final T[]a){return mapc(a, null);}public static TreeMap<Integer,Integer>mapc(final IntStream a){return a.collect( ()->new TreeMap<Integer,Integer>(),(res,v)->{res.put(v,res.getOrDefault(v,0)+1); },Map::putAll);}public static TreeMap<Long,Integer>mapc(final LongStream a){return a.collect(()->new TreeMap<Long,Integer>(),(res,v)->{res.put(v,res.getOrDefault(v, 0)+1);},Map::putAll);}public static<T>TreeMap<T,Integer>mapc(final Stream<T>a,Comparator<T> cmp){return a.collect(cmp!=null?()->new TreeMap<T,Integer>(cmp):()->new TreeMap<T, Integer>(),(res,v)->{res.put(v,res.getOrDefault(v,0)+1);},Map::putAll);}public static <T>TreeMap<T,Integer>mapc(final Stream<T>a){return mapc(a,null);}public static<T> TreeMap<T,Integer>mapc(final Collection<T>a,Comparator<T>cmp){return mapc(a.stream(), cmp);}public static<T>TreeMap<T,Integer>mapc(final Collection<T>a){return mapc(a.stream()); }public static TreeMap<Integer,List<Integer>>mapi(final int[]a){return IntStream.range(0, a.length).collect(()->new TreeMap<Integer,List<Integer>>(),(res,i)->{if(!res.containsKey(a[i])) {res.put(a[i],Stream.of(i).collect(Collectors.toList()));}else{res.get(a[i]).add(i); }},Map::putAll);}public static TreeMap<Long,List<Integer>>mapi(final long[]a){return IntStream.range(0,a.length).collect(()->new TreeMap<Long,List<Integer>>(),(res,i) ->{if(!res.containsKey(a[i])){res.put(a[i],Stream.of(i).collect(Collectors.toList())); }else{res.get(a[i]).add(i);}},Map::putAll);}public static<T>TreeMap<T,List<Integer>> mapi(final T[]a,Comparator<T>cmp){return IntStream.range(0,a.length).collect(cmp !=null?()->new TreeMap<T,List<Integer>>(cmp):()->new TreeMap<T,List<Integer>>(), (res,i)->{if(!res.containsKey(a[i])){res.put(a[i],Stream.of(i).collect(Collectors.toList())); }else{res.get(a[i]).add(i);}},Map::putAll);}public static<T>TreeMap<T,List<Integer>> mapi(final T[]a){return mapi(a,null);}public static TreeMap<Integer,List<Integer>> mapi(final IntStream a){int[]i=new int[]{0};return a.collect(()->new TreeMap<Integer, List<Integer>>(),(res,v)->{if(!res.containsKey(v)){res.put(v,Stream.of(i[0]).collect(Collectors.toList())); }else{res.get(v).add(i[0]);}i[0]++;},Map::putAll);}public static TreeMap<Long,List<Integer>> mapi(final LongStream a){int[]i=new int[]{0};return a.collect(()->new TreeMap<Long, List<Integer>>(),(res,v)->{if(!res.containsKey(v)){res.put(v,Stream.of(i[0]).collect(Collectors.toList())); }else{res.get(v).add(i[0]);}i[0]++;},Map::putAll);}public static<T>TreeMap<T,List<Integer>> mapi(final Stream<T>a,Comparator<T>cmp){int[]i=new int[]{0};return a.collect(cmp !=null?()->new TreeMap<T,List<Integer>>(cmp):()->new TreeMap<T,List<Integer>>(), (res,v)->{if(!res.containsKey(v)){res.put(v,Stream.of(i[0]).collect(Collectors.toList())); }else{res.get(v).add(i[0]);}i[0]++;},Map::putAll);}public static<T>TreeMap<T,List<Integer>> mapi(final Stream<T>a){return mapi(a,null);}public static<T>TreeMap<T,List<Integer>> mapi(final Collection<T>a,Comparator<T>cmp){return mapi(a.stream(),cmp);}public static<T>TreeMap<T,List<Integer>>mapi(final Collection<T>a){return mapi(a.stream()); }public static List<int[]>listi(final int[]a){return IntStream.range(0,a.length).mapToObj(i ->new int[]{a[i],i}).collect(Collectors.toList());}public static List<long[]>listi(final long[]a){return IntStream.range(0,a.length).mapToObj(i->new long[]{a[i],i}).collect(Collectors.toList()); }public static<T>List<Pair<T,Integer>>listi(final T[]a){return IntStream.range(0, a.length).mapToObj(i->new Pair<T,Integer>(a[i],i)).collect(Collectors.toList()); }public static List<int[]>listi(final IntStream a){int[]i=new int[]{0};return a.mapToObj(v ->new int[]{v,i[0]++}).collect(Collectors.toList());}public static List<long[]>listi(final LongStream a){int[]i=new int[]{0};return a.mapToObj(v->new long[]{v,i[0]++}).collect(Collectors.toList()); }public static<T>List<Pair<T,Integer>>listi(final Stream<T>a){int[]i=new int[]{0}; return a.map(v->new Pair<T,Integer>(v,i[0]++)).collect(Collectors.toList());}public static<T>List<Pair<T,Integer>>listi(final Collection<T>a){int[]i=new int[]{0};return a.stream().map(v->new Pair<T,Integer>(v,i[0]++)).collect(Collectors.toList());}public static String join(final int[]a){return Arrays.stream(a).mapToObj(Integer::toString).collect(Collectors.joining(SPACE)); }public static String join(final long[]a){return Arrays.stream(a).mapToObj(Long::toString).collect(Collectors.joining(SPACE)); }public static<T>String join(final T[]a){return Arrays.stream(a).map(v->Objects.toString(v)).collect(Collectors.joining(SPACE)); }public static<T>String join(final T[]a,final Function<T,String>toString){return Arrays.stream(a).map(v->toString.apply(v)).collect(Collectors.joining(SPACE));}public static<T>String join(final Collection<T>a){return a.stream().map(v->Objects.toString(v)).collect(Collectors.joining(SPACE)); }public static<T>String join(final Collection<T>a,final Function<T,String>toString) {return a.stream().map(v->toString.apply(v)).collect(Collectors.joining(SPACE)); }public static<T>String join(final Stream<T>a){return a.map(v->Objects.toString(v)).collect(Collectors.joining(SPACE)); }public static<T>String join(final Stream<T>a,final Function<T,String>toString){ return a.map(v->toString.apply(v)).collect(Collectors.joining(SPACE));}public static <T>String join(final IntStream a){return a.mapToObj(Integer::toString).collect(Collectors.joining(SPACE)); }public static<T>String join(final LongStream a){return a.mapToObj(Long::toString).collect(Collectors.joining(SPACE)); }public static List<Integer>list(final int[]a){return Arrays.stream(a).mapToObj(Integer::valueOf).collect(Collectors.toList()); }public static List<Integer>list(final IntStream a){return a.mapToObj(Integer::valueOf).collect(Collectors.toList()); }public static List<Long>list(final long[]a){return Arrays.stream(a).mapToObj(Long::valueOf).collect(Collectors.toList()); }public static List<Long>list(final LongStream a){return a.mapToObj(Long::valueOf).collect(Collectors.toList()); }public static<T>List<T>list(final Stream<T>a){return a.collect(Collectors.toList()); }public static<T>List<T>list(final Collection<T>a){return a.stream().collect(Collectors.toList()); }public static<T>List<T>list(final T[]a){return Arrays.stream(a).collect(Collectors.toList()); }public static String yesNo(final boolean res){return res?"YES":"NO";}public static String dump(Object obj){String res="";if(obj!=null){Class cl=obj.getClass();String cls=cl.getName();if(cls.startsWith("[")){res+="[";for(int i=0;;i++){try{Object o =Array.get(obj,i);String s=dump(o);if(i>0){res+=", ";}res+=s;}catch(ArrayIndexOutOfBoundsException ex){break;}}res+="]";}else if(Collection.class.isAssignableFrom(cl)){@SuppressWarnings("unchecked")final Object s=((Collection)obj).stream().map(v->dump(v)).collect(Collectors.joining(", ", "[","]"));res+=s.toString();}else if(Map.class.isAssignableFrom(cl)){@SuppressWarnings("unchecked")final Object s=((Map)obj).entrySet().stream().map(v->dump(v)).collect(Collectors.joining(", ", "{","}"));res+=s.toString();}else if(Character.class.isInstance(obj)|| Integer.class.isInstance(obj) || Long.class.isInstance(obj)|| Float.class.isInstance(obj)|| Double.class.isInstance(obj)|| String.class.isInstance(obj) ){res+=Objects.toString(obj);}else if(Map.Entry.class.isInstance(obj)){res+=dump(((Map.Entry)obj).getKey()) +"="+dump(((Map.Entry)obj).getValue());}else if(Stream.class.isInstance(obj)){@SuppressWarnings("unchecked") final Object s=((Stream)obj).map(v->dump(v)).collect(Collectors.joining(", ","[", "]"));res+=s.toString();}else{res+=Stream.concat(Arrays.stream(obj.getClass().getFields()).map(v ->{String name=v.getName();String val;try{Object o=v.get(obj);if(o!=null && v.isAnnotationPresent(Dump.class)) {Dump an=v.getAnnotation(Dump.class);Class ocl=o.getClass();val="{";for(String fn:an.fields()) {try{Field f=ocl.getField(fn);val+=fn+"="+dump(f.get(o))+", ";}catch(NoSuchFieldException nsfex){try{@SuppressWarnings("unchecked")final Method m=ocl.getMethod(fn);val+=fn+"="+dump(m.invoke(o)) +", ";}catch(NoSuchMethodException | IllegalArgumentException | InvocationTargetException nsmex){}}}if(val.endsWith(", ")){val=val.substring(0,val.length()-2);}val+="}";} else{val=dump(o);}}catch(IllegalAccessException ex){val="N/A";}return name+"="+val; }),Arrays.stream(obj.getClass().getMethods()).filter(m->m.isAnnotationPresent(Getter.class)).map(m ->{String name=m.getName();String val;try{Object o=m.invoke(obj);if(o!=null && m.isAnnotationPresent(Dump.class)) {Dump an=m.getAnnotation(Dump.class);Class ocl=o.getClass();val="{";for(String fn:an.fields()) {try{Field f=ocl.getField(fn);val+=fn+"="+dump(f.get(o))+", ";}catch(NoSuchFieldException nsfex){try{@SuppressWarnings("unchecked")final Method m1=ocl.getMethod(fn);val+=fn+"="+dump(m1.invoke(o)) +", ";}catch(NoSuchMethodException | IllegalArgumentException | InvocationTargetException nsmex){}}}if(val.endsWith(", ")){val=val.substring(0,val.length()-2);}val+="}";}else {val=dump(o);}}catch(IllegalAccessException | InvocationTargetException ex){val= "N/A";}return name+"="+val;})).collect(Collectors.joining(", ","{"+obj.getClass().getName() +": ","}"));}}if(res.length()==0){res="<null>";}return res;}}@Retention(RetentionPolicy.RUNTIME) public @interface Dump{String[]fields();}@Retention(RetentionPolicy.RUNTIME)public @interface Getter{}static class MyScanner{private StringBuilder cache=new StringBuilder();int cache_pos=0;private int first_linebreak=-1;private int second_linebreak=-1;private StringBuilder sb= new StringBuilder();private InputStream is=null;public MyScanner(final InputStream is){this.is=is;}public String charToString(final int c){return String.format("'%s'", c=='\n'?"\\n":(c=='\r'?"\\r":String.valueOf((char)c)));}public int get(){int res =-1;if(cache_pos<cache.length()){res=cache.charAt(cache_pos);cache_pos++;if(cache_pos ==cache.length()){cache.delete(0,cache_pos);cache_pos=0;}}else{try{res=is.read(); }catch(IOException ex){throw new RuntimeException(ex);}}return res;}private void unget(final int c){if(cache_pos==0){cache.insert(0,(char)c);}else{cache_pos--;}} public String nextLine(){sb.delete(0,sb.length());int c;boolean done=false;boolean end=false;while((c=get())!=-1){if(check_linebreak(c)){done=true;if(c==first_linebreak) {if(!end){end=true;}else{cache.append((char)c);break;}}else if(second_linebreak!= -1 && c==second_linebreak){break;}}if(end && c!=first_linebreak && c!=second_linebreak) {cache.append((char)c);break;}if(!done){sb.append((char)c);}}return sb.toString(); }private boolean check_linebreak(int c){if(c=='\n'|| c=='\r'){if(first_linebreak ==-1){first_linebreak=c;}else if(c!=first_linebreak && second_linebreak==-1){second_linebreak =c;}return true;}return false;}public int nextInt(){return Integer.parseInt(next()); }public long nextLong(){return Long.parseLong(next());}public boolean hasNext(){ boolean res=false;int c;while((c=get())!=-1){if(!check_linebreak(c)&& c!=' '&& c !='\t'){res=true;unget(c);break;}}return res;}public String next(){sb.delete(0,sb.length()); boolean started=false;int c;while((c=get())!=-1){if(check_linebreak(c)|| c==' '|| c=='\t'){if(started){unget(c);break;}}else{started=true;sb.append((char)c);}}return sb.toString();}public int nextChar(){return get();}public boolean eof(){int c=get(); boolean res=false;if(c!=-1){unget(c);}else{res=true;}return res;}public double nextDouble() {return Double.parseDouble(next());}}static abstract class Solver{protected String nameIn=null;protected String nameOut=null;protected boolean singleTest=false;protected MyScanner sc=null;protected PrintWriter pw=null;private int current_test=0;private int count_tests=0;protected int currentTest(){return current_test;}protected int countTests(){return count_tests;}private void process()throws IOException{if(!singleTest) {count_tests=sc.nextInt();sc.nextLine();for(current_test=1;current_test<=count_tests; current_test++){solve();pw.flush();}}else{count_tests=1;current_test=1;solve();} }abstract protected void solve()throws IOException;public void run()throws IOException {boolean done=false;try{if(nameIn!=null){if(new File(nameIn).exists()){try(FileInputStream fis=new FileInputStream(nameIn);PrintWriter pw0=select_output();){select_output(); done=true;sc=new MyScanner(fis);pw=pw0;process();}}else{throw new RuntimeException("File " +new File(nameIn).getAbsolutePath()+" does not exist!");}}}catch(IOException | AccessControlException ex){}if(!done){try(PrintWriter pw0=select_output();){sc=new MyScanner(System.in); pw=pw0;process();}}}private PrintWriter select_output()throws FileNotFoundException {if(nameOut!=null){return new PrintWriter(nameOut);}return new PrintWriter(System.out); }}static abstract class Tester{static public int getRandomInt(final int min,final int max){return(min+(int)Math.floor(Math.random()*(max-min+1)));}static public long getRandomLong(final long min,final long max){return(min+(long)Math.floor(Math.random() *(max-min+1)));}static public double getRandomDouble(final double min,final double maxExclusive){return(min+Math.random()*(maxExclusive-min));}abstract protected void testOutput(final List<String>output_data);abstract protected void generateInput(); abstract protected String inputDataToString();private boolean break_tester=false; protected void beforeTesting(){}protected void breakTester(){break_tester=true;} public boolean broken(){return break_tester;}}}
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; map<int, int> m; bool f = true; vector<int> v; while (n--) { int a; cin >> a; v.push_back(a); m[a] += 1; if (m[a] > 1) f = false; } if (!f || !m[1]) { cout << -1 << endl; continue; } vector<int> o; set<int> s; for (int a : v) { o.push_back(a); s.insert(a); for (int i = a + 1; i < 201; i++) if (!m[i] && s.find(i) == s.end()) { o.push_back(i); s.insert(i); m[i] += 1; break; } } bool r = true; int p; for (int a : s) { if (f) p = a, f = false; if (a - p > 1) { r = false; break; } p = a; } f = false; if (r) for (int a : o) { if (f) cout << ' '; cout << a; f = true; } else cout << -1; cout << endl; } return 0; }
CPP
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import heapq def restorePermutation(n, A): ans = [] unUsed = set(list(range(1, 2*n + 1))) for val in A: if not 1 <= val <= 2*n: return -1 ans.append(val) ans.append(-1) unUsed.remove(val) minHeapq = [val for val in unUsed] heapq.heapify(minHeapq) #idea use BST in future #use heap for now for i in range(1, 2*n, 2): temp = [] while minHeapq and minHeapq[0] < ans[i - 1]: temp.append(heapq.heappop(minHeapq)) if not minHeapq or (minHeapq and minHeapq[0] < ans[i - 1]): return -1 ans[i] = heapq.heappop(minHeapq) while temp: heapq.heappush(minHeapq, temp.pop()) return ans testCases = int(input()) while testCases: n = int(input()) A = [int(val) for val in input().split()] ans = restorePermutation(n, A) if ans == -1: print() print(ans) else: for val in ans: print(val, end = " ") testCases -= 1
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for _ in range(int(input())): n=int(input()) br=list(map(int,input().split())) ar=[0]*2*n for i in range(0,2*n,2): ar[i]=br[i//2] se=set(br) for i in range(0,2*n,2): for k in range(ar[i]+1,3*n): if(not(k in se)): ar[i+1]=k se.add(k) break bbc=ar.copy() bbc.sort() ccr=[] for zz in range(1,2*n+1): ccr.append(zz) if(bbc==ccr): print(*ar) else: print(-1)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.LinkedList; import java.util.StringTokenizer; public class RestoringPermutation { public static void main(String[] args) { FastReader input=new FastReader(); int t=input.nextInt(); while(t-->0) { int n=input.nextInt(); LinkedList<Integer> b=new LinkedList<>(); HashSet<Integer> set=new HashSet<>(); LinkedList<Integer> list=new LinkedList<>(); for(int i=0;i<2*n;i++) { list.add(i+1); } int flag=0; for(int i=0;i<n;i++) { int v=input.nextInt(); b.add(v); if(set.contains(v)) { flag=1; } else { set.add(v); list.remove((Object)v); } } if(flag==1) { System.out.println(-1); } else { int i=0; int f=0; while(i<2*n) { int g=next(list,b.get(i)); if(g==-1) { f=1; break; } else { b.add(i + 1, list.get(g)); list.remove(g); i += 2; } } if(f==1) { System.out.println(-1); } else { for(int j=0;j<b.size();j++) { System.out.print(b.get(j)+" "); } System.out.println(); } } } } public static int next(LinkedList<Integer> arr, int target) { int start = 0, end = arr.size() - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr.get(mid) <= target) { start = mid + 1; } else { ans = mid; end = mid - 1; } } return ans; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import sys input = sys.stdin.readline def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) tests = inp() testcount = 0 while testcount < tests: n = inp() b = inlt() if 1 not in b or 2*n in b: print(-1) else: arr = [] for elem in b: i = 1 while i < 4*n: if elem+i not in b and elem+i not in arr: arr.append(elem+i) i += 4*n else: i += 1 string = '' i = 0 while i < n: string += str(b[i]) + ' ' + str(arr[i]) + ' ' i += 1 if max(max(b),max(arr)) > 2*n: print(-1) else: print(string[:len(string)-1]) testcount += 1
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.util.*; public class MyClass { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int[] a = new int[n]; int[] b = new int[2*n+1]; for(int i=0;i<n;i++) { a[i] = sc.nextInt(); b[a[i]]=1; } ArrayList<Integer> arr = new ArrayList<Integer>(); for(int i=0;i<n;i++) { arr.add(a[i]); int d = 0; for(int j=1;j<2*n+1;j++) { if(j>a[i]&&b[j]==0) { d++; arr.add(j); b[j]=1; break; } } if(d==0) { arr.add(0); } } int dd=0; for(int i=0;i<2*n;i++) { if(arr.get(i)==0) { dd++; break; } } if(dd==1) { System.out.println(-1); } else { for(int i=0;i<2*n;i++) { System.out.print(arr.get(i)+" "); } System.out.println(); } } } }
JAVA
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
for t in range(int(input())): n = int(input()) b = list(map(int, input().split())) used = [False]*(n*2) a = [] for x in b: used[x-1] = True for x in b: for i in range(x+1, 2*n+1): if not used[i-1]: a.append(x) a.append(i) used[i-1] = True break else: print(-1) break else: print(*a)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
I=input for _ in[0]*int(I()): n=2*int(I());a=[0]*n;b=a[::2]=*map(int,I().split()),;c={*range(n+1)}-{*b};i=1 try: for x in b:y=a[i]=min(c&{*range(x,n+1)});c-={y};i+=2 except:a=-1, print(*a)
PYTHON3
1315_C. Restoring Permutation
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). The first line of each test case consists of one integer n β€” the number of elements in the sequence b (1 ≀ n ≀ 100). The second line of each test case consists of n different integers b_1, …, b_n β€” elements of the sequence b (1 ≀ b_i ≀ 2n). It is guaranteed that the sum of n by all test cases doesn't exceed 100. Output For each test case, if there is no appropriate permutation, print one number -1. Otherwise, print 2n integers a_1, …, a_{2n} β€” required lexicographically minimal permutation of numbers from 1 to 2n. Example Input 5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 Output 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
2
9
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; public class zz { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int b[] = new int[n]; int a[] = new int[2 * n]; TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i < a.length; i++) { ts.add(i + 1); } for (int i = 0; i < b.length; i++) { b[i] = Integer.parseInt(st.nextToken()); a[2*i]=b[i]; ts.remove(b[i]); } boolean f=true; for (int i = 0; i < b.length; i++) { if(ts.ceiling(b[i])==null) { f=false; break; } a[2*i+1]=ts.ceiling(b[i]); ts.remove(a[2*i+1]); } if(f) { for(int e:a) System.out.print(e+" "); System.out.println(); } else System.out.println(-1); } } }
JAVA