OpenJudge上的一道题,
遇到的问题是Wrong Answer,不知道是哪个地方考虑不周没想到。
具体题目:
在幼儿园中,老师安排小朋友做一个排队的游戏。首先老师精心的把数目相同的小男孩和小女孩编排在一个队列中,每个小孩按其在队列中的位置发给一个编号(编 号从0开始)。然后老师告诉小朋友们,站在前边的小男孩可以和他后边相邻的小女孩手拉手离开队列,剩余的小朋友重新站拢,再按前后相邻的小男孩小女孩手拉 手离开队列游戏,如此往复。由于教师精心的安排,恰好可以保证每两个小朋友都能手拉手离开队列,并且最后离开的两个小朋友是编号最小的和最大的两个小朋 友。(注:只有小男孩在前,小女孩在后,且他们两之间没有其他的小朋友,他们才能手拉手离开队列)。请根据老师的排队,按小女孩编号从小到大的顺序,给出 所有手拉手离开队列的小男孩和小女孩的编号对。
样例输入
((()(())())(()))
样例输出
2 3
5 6
4 7
8 9
1 10
12 13
11 14
0 15
我的代码:
#include<iostream>
using namespace std;
char judge(char c[]) {
int i = 0 ;
int j=0, k=0;
char *sptr;
sptr = c;
while (sptr[i] != ')'&&i<101) {
i++;
}
c[i] = ' ';//此时输出的是遍历过来的第一个右括号,改为空格
k = i;//存放该右括号位置
while (sptr[i] != '(') {
i--;
}
c[i] = ' ';//此时输出的是从获取的右括号起倒数过来的第一个左括号,改为空格
j = i;//存放该左括号位置
cout << j << ' ' << k << endl;
for (int y = 0; y <= k; y++) {//判断是否还有剩余
if (c[y] != ' ') {
break;
}
else {
return 0;
}
}
return judge(c);
}
int main() {
char c[101];
cin.getline(c, 101,'\n');
judge(c);
return 0;
}
Just use a stack for this problem:
Recursive code, see @bordertownmadman’s explanation:
If you use recursive thinking to solve it, it should be like this
Define a process called pairing and its steps
Represented by algorithm
Initial call (assuming the list must not be empty)
The recursive calling method does not use many loops. If you like to use loops, you can use the stack method instead of recursion (that is, derecursion, or expansion recursion)
I hope you can understand the algorithm and then write your own code to test it. If there is a problem with the test code, take it out and continue to analyze it for you.
js6 code
If you have the latest version of iojs, you can save it directly to a file and run it; if it is nodejs, you may need to add some parameters when running... But if you have a newer browser (Chrome, or IE11, etc.), You can paste and run it directly in the developer window of the browser.
Results