题解 | #火车进站#

火车进站

http://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char list[6000][10]; //出站
int stack[10];       //车站
int train[10];       //火车
int kind = 0;
int n;
//用回溯算法遍历可能情况,保存为字符串数组,用qsort进行排序
void DFS(int pos, int top, int index);
int cmp_char(const void *_a, const void *_b);
int main()
{
  while (scanf("%d", &n) != EOF)
  {
    for (int i = 0; i < n; i++)
    {
      scanf("%d", &train[i]);
    }
    int top = -1;
    int index = 0;
    DFS(0, top, index);
    qsort(list + 1, kind, sizeof(list[1]), cmp_char);

    for (int i = 1; i <= kind; i++)
    {
      for (int j = 0; j < n; j++)
      {
        printf("%c ", list[i][j]);
      }
      printf("\n");
    }
  }

  return 0;
}

void DFS(int pos, int top, int index) //出站数组中位置,站顶,火车数组位置
{
  if (pos == n)
  {
    kind++;
    for (int i = 0; i < n; i++)
    {
      list[kind][i] = list[0][i];
    }
    return;
  }
//进站
  if (index < n)
  {
    stack[++top] = train[index++];
    DFS(pos, top, index);
    top--;
    index--;
  }
//出站
  if (top >= 0)
  {
    list[0][pos++] = stack[top--] + '0';
    DFS(pos, top, index);
    stack[++top] = list[0][--pos] - '0';
  }
}

int cmp_char(const void *_a, const void *_b)
{
  char *a = (char *)_a;
  char *b = (char *)_b;
  return strcmp(a, b);
}
全部评论
牛啊牛啊
点赞 回复 分享
发布于 2023-04-11 16:50 广东

相关推荐

点赞 评论 收藏
分享
07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
评论
2
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务