正确的数组
假设我们有一个长度为N的数组,用大写字母组成 字母A,B和C。如果数组之间 每两个C字母在数组中一个接一个地出现 A字母多于B字母。我的工作是发现是否 不是给定的数组是“正确的”,如果是这样,我应该打印出“正确的”, 否则我应该打印多少个(在Cs之间) 给定条件不正确(B大于As)。
输入:在第一行中,我们输入数组N中的字母数(1
200)。在下一行中,我们输入的数组不为空 中间的空格。 输出:单行打印答案。
示例:
输入:16 ABBCAABCACBAAACB 输出:RIGHT
输入:15 ABBCABCACBAAACB 输出:1
输入:14 CABCABBCBAABBC 输出:3
现在,我已经尝试解决此问题,但是第三个示例对我不起作用-我得到2的输出,并且如上所述,我应该得到3,除此之外-编译起来很好。
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
char Ar[N];
int A = 0;
int B = 0;
int piece = 0;
int attempt = 0;
for (int i = 0; i < N; i++) {
cin >> Ar[i];
}
for (int i = 0; i < N; i++) {
if (Ar[i] == 'C') {
for (int j = i + 1; i < N; j++) {
if (Ar[j] == 'A') {
A++;
} else if (Ar[j] == 'B') {
B++;
} else if (Ar[j] == 'C') {
i = j;
break;
}
}
if (A > B) {
piece++;
attempt++;
} else if (A <= B) {
attempt++;
}
A = 0;
B = 0;
}
}
if (piece == attempt) {
cout << "RIGHT";
} else {
cout << attempt - piece;
}
return 0;
}
答案 0 :(得分:3)
问题在于情况
} else if (Ar[j] == 'C') {
i = j;
break;
}
原因是,一旦回到主循环i
将递增,因此结尾C
将不被视为新组的开始。您的代码基本上在检查其他所有块。
您应该设置
i = j-1;
相反,因此在递增i
之后将是C
的索引。
另外,在评估节时,应将A
和B
初始化为零。
答案 1 :(得分:2)
您遇到了一些问题,如下面的代码注释所述:
int N;
cin >> N;
std::vector<char> Ar(N);
for (int i = 0; i < N; i++) {
cin >> Ar[i];
}
int piece = 0;
int attempt = 0;
for (int i = 0; i < N - 1; i++) {
if (Ar[i] != 'C') {
// Skip letters until the first C
continue;
}
int A = 0;
int B = 0;
int j = i + 1;
for (; j < N; j++) {
if (Ar[j] == 'A') {
A++;
} else if (Ar[j] == 'B') {
B++;
} else if (Ar[j] == 'C') {
// We only account for blocks between Cs
attempt++;
if (A > B) {
piece++;
}
break;
}
}
// Next piece starts at j, i will be incremented by outer loop
i = j - 1;
}
答案 2 :(得分:1)
#include <iostream>
using namespace std;
int main() {
int numChars;
cin >> numChars;
char array[numChars];
for (int i = 0; i < numChars; ++i) {
cin >> array[i];
}
int numBrokenPieces = 0;
int numAs = 0;
int numBs = 0;
bool inPiece = false;
for (int i = 0; i < numChars; ++i) {
if (array[i] == 'C') {
if (!inPiece) {
inPiece = true;
continue;
} else {
if (numBs >= numAs) {
++numBrokenPieces;
}
numAs = 0;
numBs = 0;
}
} else {
if (inPiece) {
if (array[i] == 'A') {
++numAs;
} else if (array[i] == 'B') {
++numBs;
}
}
}
}
if (numBrokenPieces == 0) {
cout << "RIGHT";
} else {
cout << numBrokenPieces;
}
return 0;
}
答案 3 :(得分:1)
好吧,您也可以采用其他方法:
string str;
bool counting = false;
int counter = 0, notRightCounter = 0;
cout << "String: ";
cin >> str; // user enters whole string at once
for (char& c : str) { // for each char in string
if (c == 'C') { // start or stop counting when C is found
counting = !counting;
if (!counting && counter <= 0) { // Check if piece between Cs is right
notRightCounter++;
counting = !counting;
}
counter = 0;
continue; // Continue to next char after 'C'
}
if (counting) // Keeping count of A's and B's
switch (c) {
case 'A':
counter++;
break;
case 'B':
counter--;
break;
}
}
// Print results
if (notRightCounter != 0)
cout << "Not right! " << "Not right counter: " << notRightCounter;
else
cout << "Right!";