10
5
1 2 3 5 8
A
5
8 5 3 2 1
A
5
8 5 3 2 1
abcd
5
8 5 3 2 1
ABCDEFG
5
5 4 3 2 1
ABCDE
5
5 4 3 2 1
A a B b C c D d E e
1
13
ABCD
1
1836311903
aaaaaaaaaabbbbbbbbbbcccccccccccDdddddddddddddddddddd
1
4
ABC
1
2
a
hi there, I'm new to c and cpp but below is the solution i have using cpp. i have no idea why my string has some trailing characters at the end. I tried to null terminate the string as well but it does not seemed to have any effect. THANKS for your help in advance..
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int findpos(long a, long b[]) {
int i = 45;
while(i >= 0) {
if(b[i] == a) {
return i;
}
i--;
}
return i;
}
int main() {
long fib[46];
long next = 0;
long first = 1;
long second = 1;
int j = 0;
for (long c = 1 ; next < 1836311904 ; c++ ) {
if ( c <= 1 )
next = c;
else {
next = first + second;
first = second;
second = next;
}
fib[j] = next;
j++;
}
int T,N;
cin >> T;
for(int i = 0; i < T; i++) {
cin >> N;
long pos[N];
long m = 0;
for(int j = 0; j < N; j++) {
cin >> pos[j];
m = max(m, pos[j]);
}
string line;
getline(cin, line);
getline(cin, line);
int p = findpos(m, fib);
char ans[p+1];
int j = 0;
for(int k = 0; k < p+1; k++) {
ans[k] = ' ';
}
int k = 0;
int len = line.length();
while (k < len && j < N) {
if(isupper(line[k])) {
int p = findpos(pos[j], fib);
ans[p] = line[k];
j++;
}
k++;
}
cout << ans << endl;
}
}
You need to increase the size of ans. For the first sample input your code is generating p=12, for the second p=16. Those aren't large enough to hold the output.
Check input and AC output for thousands of problems on uDebug!