B - Insert Editorial by en_translator
For beginners
- If you are new to learning programming and do not know where to start, please try Problem A "Welcome to AtCoder" from practice contest. There you can find a sample code for each language.
- Also, if you are not familiar with problems in programming contests, we recommend you to try some problems in "AtCoder Beginners Selection".
- 「C++入門 AtCoder Programming Guide for beginners (APG4b)」 is a C++ tutorial for competitive programmers. Sadly, this is only in Japanese too.
- 「Python入門 AtCoder Programming Guide for beginners (APG4bPython)」 is a Python tutorial for competitive programmers. Again, this is only in Japanese.
Approach 1. Actually construct the sequence \(B\)
After receiving \(N,K,X\), and the sequence \(A\), we can insert \(X\) after the \(K\)-th element of \(A\).
For example, if you use the list
type of Python, you can use the insert
method.
For other languages, please refer to articles on array handling or language reference of the language.
Sample code (Python):
n,k,x = map(int,input().split())
a = list(map(int,input().split()))
a.insert(k,x)
print(*a)
Regarding the print(*a)
part, one can prepend *
before the list name to print it without unnecessary brackets.
Approach 2. Instead of actually constructing the sequence \(B\), print it sequentially
Actually, we can properly output the result without actually constructing the sequence \(B\) nor even storing the array \(A\).
Specifically, receive each element of the sequence \(A\) and directly print it. After printing the \(K\)-th element, print \(X\). Finally, receive and print the remaining elements of \(A\).
Sample code (C++):
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,k,x;
cin >> n >> k >> x;
for(int i=0;i<n;i++){
int a;
cin >> a;
if(i!=0){cout << " ";}
cout << a;
if(i==(k-1)){
cout << " " << x;
}
}cout << "\n";
return 0;
}
posted:
last update: