头一次栈接触这东西,纠结了我四五天。。
刚开始是没理解题,没注意reorganize的意思....重组啊!!!神马是重组,就是乱七八糟的呗``
进的时候是1,2,3,4,5……,可以不在C中停留,一个一个进的话,到B中就是1,2,3,4,5……
要是几组的话,情况就多了,C中会有积累。例如B是3,2,1,4,5.那么就是123|4|5
学了不少,但主要的还是栈的思想
代码层面嘛,那个0比较有意思。
就这些吧,上代码
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <algorithm> using namespace std; int main() { int stack[1005], A, top; //栈,也就是C车站 int station_B[1005],B; //进B的顺序,也就是出栈的顺序 int n, i; int ok = 1; start:; scanf("%d", &n); while( n ) { memset(station_B,0,sizeof(station_B)); ok = 1; scanf("%d", &station_B[1]); if (station_B[1] == 0) //当B[1]为0,换车厢数n,goto到scanf n { printf("\n"); goto start; } else { for (i = 2; i <= n; i++) { scanf("%d", &station_B[i]); } A = B = 1; top = 0; //注意top初值 while (B <= n) //进栈顺序是1 2 3 4 5 { if (station_B[B] == A) //若B【】==A,说明进一个就出一个,栈里没有存 { A++; B++; } else if (top && station_B[B] == stack[top]) //栈的最顶元素在B[]中找到(位于最后一个单个进入的后面),若相等的话 { //top向下,B向右,再判断更早的元素stack[top-1]是否还等于b[B+1] B++; top--; } else if (A <= n) //B【】!=A,说明栈里有存数,并且是从小到大存,1,2,3...因为进栈是那个顺序 { stack[++top] = A++; //从小到大进栈 } else { ok = 0; break; } } } printf("%s\n", ok ? "Yes" : "No"); } system("pause"); return 0;
}