PTA 2023-2024-1-数据结构练习题重现(编程题)

7-1 两个有序序列的中位数

已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列A0​,A1​,⋯,AN−1​的中位数指A(N−1)/2​的值,即第⌊(N+1)/2⌋个数(A0​为第1个数)。

输入格式:

输入分三行。第一行给出序列的公共长度N(0<N≤100000),随后每行输入一个序列的信息,即N个非降序排列的整数。数字用空格间隔。

输出格式:

在一行中输出两个输入序列的并集序列的中位数。

输入样例1:

5
1 3 5 7 9
2 3 4 5 6

输出样例1:

4

输入样例2:

6
-100 -10 1 1 1 1
-50 0 2 3 4 5

输出样例2:

1

 代码示例:

#include <stdio.h>
typedef struct {
    int *elem;
    int length;
}SqList;
SqList create(int n);
SqList merge(SqList la,SqList lb);
int main(){
    SqList la,lb,lc;
    int n;
    scanf("%d\n",&n);
    la=create(n);
    lb=create(n);
    lc = merge(la,lb);
    printf("%d\n",lc.elem[(lc.length-1)/2]);
    return 0;
}

SqList create(int n){
    SqList L;
    L.elem = (int*)malloc(n*sizeof(int));
    L.length = n;
    for(int i = 0;i<n;i++){
        scanf("%d",&L.elem[i]);
    }
    return L;
}
SqList merge(SqList la,SqList lb){
    SqList lc;
    lc.elem=(int*)malloc(sizeof(int)*(la.length+lb.length));
    lc.length = la.length+lb.length;
    int i=0,j=0,k=0;
    while(i<la.length&&j<lb.length){
        if(la.elem[i]<=lb.elem[j]){
            lc.elem[k++]=la.elem[i++];
        }else{
            lc.elem[k++]=lb.elem[j++];
        }
    }
    while(i<la.length){
        lc.elem[k++]=la.elem[i++];
    }
    while(j<lb.length){
        lc.elem[k++]=lb.elem[j++];
    }
    return lc;
}

7-2 求链式线性表的倒数第K项

给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。

输入格式:

输入首先给出一个正整数K,随后是若干非负整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。

输出格式:

输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息NULL

输入样例:

4 1 2 3 4 5 6 7 8 9 0 -1

输出样例: 

7

代码示例: 

#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct LNode{
    ElemType data;
    struct LNode *next;
}LNode,*LinkList;
LinkList create();
LinkList search(LinkList L,int k);
int main(){
    int k;
    scanf("%d",&k);
    LinkList L = create();
    LinkList p =search(L,k);
    if(p) printf("%d",p->data);
    else printf("NULL");
    return 0;
}
LinkList create(){
    LinkList L,tail,s;
    L = (LinkList)malloc(sizeof(LNode));
    tail = L;
    int num;
    scanf("%d",&num);
    while(num>=0){
        s = (LinkList)malloc(sizeof(LNode));
        s->data = num;
        tail->next = s;
        tail = s;
        scanf("%d",&num);
    }
    tail ->next = NULL;
    return L;
}
LinkList search(LinkList L,int k){
    LinkList p,q;
    p = L,q = L;
    int i = 0;
    while(p&&i<k){
        p=p->next;
        i++;
    }
    if(!p) return NULL;
    while(p){
        p = p->next;
        q = q->next;
    }
    return q;
}

7-2 输出全排列

请编写程序输出前n个正整数的全排列(n<10),并通过9个测试用例(即n从1到9)观察n逐步增大时程序的运行时间。

输入格式:

输入给出正整数n(<10)。

输出格式:

输出1到n的全排列。每种排列占一行,数字间无空格。排列的输出顺序为字典序,即序列a1​,a2​,⋯,an​排在序列b1​,b2​,⋯,bn​之前,如果存在k使得a1​=b1​,⋯,ak​=bk​ 并且 ak+1​<bk+1​。

输入样例:

3

输出样例: 

123
132
213
231
312
321

代码示例: 

#include <stdio.h>
#include <stdlib.h>
int visited[10];
int p[10];
void rank(int i,int n);
int main(){
    int n;
    scanf("%d",&n);
    rank(0,n);
    return 0;
}
void rank(int i,int n){
    if(i>=n){
        for(int j = 0;j<n;j++){
            printf("%d",p[j]);
        }
        printf("\n");
        return;
    }
    for(int j = 1;j<=n;j++){
        if(visited[j] == 0){
            p[i]=j;
            visited[j] = 1;
            rank(i+1,n);
            visited[j] = 0;
        }
    }
}

7-4 还原二叉树

给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

输入格式:

输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。

输出格式:

输出为一个整数,即该二叉树的高度。

输入样例:

9
ABDFGHIEC
FDHGIBEAC

输出样例: 

5

代码示例:

 

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct BiTNode{
    ElementType data;
    struct BiTNode *lchild;
    struct BiTNode *rchild;
}BiTNode,*BiTree;

BiTree CreatBinTree(char *pre, char *in, int n);
int Height( BiTree T );

int main()
{
    int N;
    scanf("%d", &N);
    char prelist[51];
    char inlist[51];
    scanf("%s", prelist);
    scanf("%s", inlist);
    BiTree T = CreatBinTree(prelist, inlist, N);
    printf("%d", Height(T));
    return 0;
}

int Height( BiTree T )
{
    if(!T) return 0;
    int lHeight = Height(T->lchild);
    int rHeight = Height(T->rchild);
    return (lHeight > rHeight ? lHeight : rHeight) + 1;
}

BiTree CreatBinTree(char *pre, char *in, int n)
{
    if(n <= 0) return NULL;
    BiTree T = (BiTree)malloc(sizeof(BiTNode));
    T->data = pre[0];
    int i;
    for(i = 0; i < n; i++){
        if(in[i] == pre[0]) break;
    }
    T->lchild = CreatBinTree(pre+1, in, i);
    T->rchild = CreatBinTree(pre+i+1, in+i+1, n-i-1);
    return T;
}

7-3 树的遍历

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例: 

4 1 6 3 5 7 2

代码示例: 

#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
    int val;
    struct TreeNode* left;
    struct TreeNode* right;
} TreeNode;
typedef struct QueueNode {
    TreeNode* node;
    struct QueueNode* next;
} QueueNode;

typedef struct {
    QueueNode* front;
    QueueNode* rear;
} Queue;

// 创建二叉树
TreeNode* buildTree(int* postorder, int* inorder, int postStart, int postEnd, int inStart, int inEnd)
{
    if (postStart > postEnd || inStart > inEnd) {
        return NULL;
    }
    int rootVal = postorder[postEnd];
    TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
    root->val = rootVal;
    int rootIndex = inStart;
    while (inorder[rootIndex] != rootVal) {
        rootIndex++;
    }
    int leftSize = rootIndex - inStart;
    root->left = buildTree(postorder, inorder, postStart, postStart + leftSize - 1, inStart, rootIndex - 1);
    root->right = buildTree(postorder, inorder, postStart + leftSize, postEnd - 1, rootIndex + 1, inEnd);

    return root;
}

// 入队
void enqueue(Queue* queue, TreeNode* node)
{
    QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
    newNode->node = node;
    newNode->next = NULL;
    if (queue->rear == NULL) {
        queue->front = newNode;
        queue->rear = newNode;
    } else {
        queue->rear->next = newNode;
        queue->rear = newNode;
    }
}

// 出队
TreeNode* dequeue(Queue* queue)
{
    if (queue->front == NULL) {
        return NULL;
    }
    TreeNode* node = queue->front->node;
    QueueNode* temp = queue->front;
    queue->front = queue->front->next;
    if (queue->front == NULL) {
        queue->rear = NULL;
    }
    free(temp);
    return node;
}

// 层序遍历
void levelOrderTraversal(TreeNode* root)
{
    Queue queue;
    queue.front = NULL;
    queue.rear = NULL;
    enqueue(&queue, root);

    while (queue.front != NULL) {
        TreeNode* node = dequeue(&queue);
        printf("%d", node->val);
        if (node->left != NULL) {
            enqueue(&queue, node->left);
        }
        if (node->right != NULL) {
            enqueue(&queue, node->right);
        }
        if (queue.front != NULL) {
            printf(" ");
        }
    }
}

int main()
{
    int N;
    scanf("%d", &N);
    int* postorder = (int*)malloc(N * sizeof(int));
    int* inorder = (int*)malloc(N * sizeof(int));
    for (int i = 0; i < N; i++) {
        scanf("%d", &postorder[i]);
    }
    for (int i = 0; i < N; i++) {
        scanf("%d", &inorder[i]);
    }
    TreeNode* root = buildTree(postorder, inorder, 0, N - 1, 0, N - 1);
    levelOrderTraversal(root);
    free(postorder);
    free(inorder);
    return 0;
}

7-6 根据后序和中序遍历输出先序遍历

本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。

输入格式:

第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。

输出格式:

在一行中输出Preorder: 以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。

输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例: 

Preorder: 4 1 3 2 6 5 7

代码示例:

 

#include <stdio.h>
#include <stdlib.h>

typedef int ElementType;
typedef struct BiTNode{
    ElementType data;
    struct BiTNode *lchild;
    struct BiTNode *rchild;
}BiTNode,*BiTree;

BiTree CreatBinTree(int *post, int *in, int n);
void preorder( BiTree T );

int isFirst = 1;

int main()
{
    int N;
    scanf("%d", &N);
    int postlist[30];
    int inlist[30];
    for(int i = 0; i < N; i++){
        scanf("%d", &postlist[i]);
    }
    for(int i = 0; i < N; i++){
        scanf("%d", &inlist[i]);
    }
    BiTree T = CreatBinTree(postlist, inlist, N);
    printf("Preorder: ");
    preorder(T);
    return 0;
}

void preorder( BiTree T )
{
    if(T){
        if(isFirst){
            printf("%d", T->data);
            isFirst = 0;
        }else{
            printf(" %d", T->data);
        }
        preorder(T->lchild);
        preorder(T->rchild);
    }
}

BiTree CreatBinTree(int *post, int *in, int n)
{
    if(n <= 0) return NULL;
    BiTree T = (BiTree)malloc(sizeof(BiTNode));
    T->data = post[n-1];
    int i;
    for(i = 0; i < n; i++){
        if(in[i] == post[n-1]) break;
    }
    T->lchild = CreatBinTree(post, in, i);
    T->rchild = CreatBinTree(post + i, in + i + 1, n - i - 1);
    return T;
}

7-7 路径判断

给定一个有N个顶点和E条边的无向图,请判断给定的两个顶点之间是否有路径存在。
假设顶点从0到N−1编号。

输入格式:

输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。

随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。

最后一行给出两个顶点编号i,j(0≤i,j<N),i和j之间用空格分隔。

输出格式:

如果i和j之间存在路径,则输出"There is a path between i and j.",

否则输出"There is no path between i and j."。

输入样例1:

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 3

输出样例1: 

There is a path between 0 and 3.

输入样例2: 

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 6

输出样例2: 

There is no path between 0 and 6.

代码示例: 

#include <stdio.h>
#include <stdbool.h>
#define MAX_VERTEX_NUM 10
#define MAX_EDGE_NUM 20

typedef struct{
    int u;
    int v;
} Edge;

typedef struct{
    int vertices[MAX_VERTEX_NUM];
    int edges[MAX_EDGE_NUM][2];
    int vexnum;
    int edgenum;
} Graph;

void initGraph(Graph *G,int N,int E){
    G->vexnum = N;
    G->edgenum = E;
    for(int i = 0;i<N;i++){
        G->vertices[i] = i;
    }
    for(int i = 0;i<E;i++){
        scanf("%d %d",&(G->edges[i][0]),&(G->edges[i][1]));
    }
}

bool hasPath(Graph* G,int i,int j,bool visited[]){
    if(i == j){
        return true;
    }
    visited[i] = true;
    for(int k = 0;k<G->edgenum;k++){
        int u = G->edges[k][0];
        int v = G->edges[k][1];
        if((u==i&&v==j)||(u==j&&v==i)){
            return true;
        }
        if(u==i&&!visited[v]){
            if(hasPath(G,v,j,visited)){
                return true;
            }
        }
        if(v == i&&!visited[u]){
            if(hasPath(G,u,j,visited)){
                return true;
            }
        }
    }
    return false;
}

int main(){
    int N,E;
    scanf("%d %d",&N,&E);
    Graph G;
    initGraph(&G,N,E);
    int i,j;
    scanf("%d %d",&i,&j);
    bool visited[MAX_VERTEX_NUM] = {false};
    if(hasPath(&G,i,j,visited)){
        printf("There is a path between %d and %d.\n",i,j);
    }else{
        printf("There is no path between %d and %d.\n",i,j);
    }
    return 0;
}

7-8 生化危机

人类正在经历一场生化危机,许多城市已经被病毒侵袭,这些城市中的人们为了避免感染病毒,计划开车逃往其他没有被病毒入侵的城市(安全城市)。有些城市之间有公路直达,有些没有。虽然他们知道哪些城市是安全的,但是不知道有没有一条安全路径能够到达安全城市(只有该路径上经过的所有城市都是安全的,该路径才是安全路径)。请你编写一个程序帮助他们判断。

输入格式:

输入第一行为三个正整数,分别表示所有城市个数m(m<=100)、安全城市个数n(m<=50)、公路个数k(k<=100)。随后一行给出n个安全城市的编号。随后k行,每一行给出两个整数,表示连接一条公路的两个城市编号。最后一行输入两个整数,分别表示当前所在城市s、目标城市d。每行整数之间都用空格分隔。

输出格式:

若目标城市已被病毒入侵(非安全城市),输出"The city d is not safe!";若目标城市为安全城市且从当前所在城市能够经过一条安全路径到达目标城市,输出"The city d can arrive safely!";若目标城市为安全城市但是从当前所在城市没有一条安全路径到达目标城市,输出"The city d can not arrive safely!",d为目标城市编号。

输入样例1:

5 2 5
3 4
0 1
0 2
0 4
1 2
2 4
0 4

输出样例1:

The city 4 can arrive safely! 

输入样例2:

5 2 5
3 4
0 1
0 2
0 4
1 2
2 4
0 3 

输出样例2: 

The city 3 can not arrive safely! 

输入样例3:

5 2 5
3 4
0 1
0 2
0 4
1 2
2 4
0 1 

输出样例3: 

The city 1 is not safe! 

代码示例:

 

#include <stdio.h>
#include <stdbool.h>

#define MAX_CITIES 100

// 深度优先搜索
bool isSafePath(int graph[MAX_CITIES][MAX_CITIES], bool visited[MAX_CITIES],
                int current, int target)
{
    // 如果当前城市是目标城市,返回 true
    if (current == target)
        return true;
    // 标记当前城市为已访问
    visited[current] = true;
    // 遍历当前城市的邻居城市
    for (int neighbor = 0; neighbor < MAX_CITIES; ++neighbor)
    {
        // 如果邻居城市未被访问,则递归判断是否存在安全路径
        if (graph[current][neighbor] && !visited[neighbor])
        {
            if (isSafePath(graph, visited, neighbor, target))
                return true;
        }
    }
    // 如果无法找到安全路径,返回 false
    return false;
}
int main()
{
    int m, n, k;
    scanf("%d %d %d", &m, &n, &k);
    int safeCities[MAX_CITIES];
    for (int i = 0; i < n; ++i)
        scanf("%d", &safeCities[i]);
    int graph[MAX_CITIES][MAX_CITIES] = {0};
    for (int i = 0; i < k; ++i)
    {
        int city1, city2;
        scanf("%d %d", &city1, &city2);
        graph[city1][city2] = 1;
        graph[city2][city1] = 1;
    }

    int currentCity, targetCity;
    scanf("%d %d", &currentCity, &targetCity);
    bool visited[MAX_CITIES] = {false};
    // 如果目标城市是非安全城市,输出 "The city d is not safe!"
    bool isSafe = false;
    for (int i = 0; i < n; ++i)
    {
        if (targetCity == safeCities[i])
        {
            isSafe = true;
            break;
        }
    }
    if (!isSafe)
    {
        printf("The city %d is not safe!\n", targetCity);
    }
    else
    {
        // 判断是否存在安全路径
        if (isSafePath(graph, visited, currentCity, targetCity))
            printf("The city %d can arrive safely!\n", targetCity);
        else
            printf("The city %d can not arrive safely!\n", targetCity);
    }
    return 0;
}

7-9 最短路径

给定一个有N个顶点和E条边的无向图,顶点从0到N−1编号。请判断给定的两个顶点之间是否有路径存在。如果存在,给出最短路径长度。
这里定义顶点到自身的最短路径长度为0。
进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。

输入格式:

输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。
随后E行,每行给出一条边的两个顶点。每行中的数字之间用1空格分隔。
最后一行给出两个顶点编号i,j(0≤i,j<N),i和j之间用空格分隔。

输出格式:

如果i和j之间存在路径,则输出"The length of the shortest path between i and j is X.",X为最短路径长度,
否则输出"There is no path between i and j."。

输入样例1:

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 3

输出样例1:

The length of the shortest path between 0 and 3 is 2.

输入样例2:

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 6

输出样例2:

There is no path between 0 and 6.

代码示例:

 

#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
#define MAX_VERTEX_NUM 10
#define MAX_EDGE_NUM 20
typedef struct {
    int u;
    int v;
} Edge;
typedef struct {
    int vertices[MAX_VERTEX_NUM];
    int edges[MAX_EDGE_NUM][2];
    int vexnum;
    int edgenum;
} Graph;
void initGraph(Graph* G, int N, int E) {
    G->vexnum = N;
    G->edgenum = E;
    for (int i = 0; i < N; i++) {
        G->vertices[i] = i;
    }
    for (int i = 0; i < E; i++) {
        scanf("%d %d", &(G->edges[i][0]), &(G->edges[i][1]));
    }
}
int findShortestPath(Graph* G, int i, int j) {
    int dist[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
    // 初始化距离矩阵
    for (int u = 0; u < G->vexnum; u++) {
        for (int v = 0; v < G->vexnum; v++) {
            if (u == v) {
                dist[u][v] = 0; // 自身到自身的距离为0
            } else {
                dist[u][v] = INT_MAX; // 初始化为无穷大
            }
        }
    }
    // 根据边信息更新距离矩阵
    for (int k = 0; k < G->edgenum; k++) {
        int u = G->edges[k][0];
        int v = G->edges[k][1];
        dist[u][v] = 1;
        dist[v][u] = 1;
    }
    // Floyd-Warshall算法计算最短路径
    for (int k = 0; k < G->vexnum; k++) {
        for (int u = 0; u < G->vexnum; u++) {
            for (int v = 0; v < G->vexnum; v++) {
                if (dist[u][k] != INT_MAX && dist[k][v] != INT_MAX && dist[u][k] + dist[k][v] < dist[u][v]) {
                    dist[u][v] = dist[u][k] + dist[k][v];
                }
            }
        }
    }
    return dist[i][j];
}
int main() {
    int N, E;
    scanf("%d %d", &N, &E);
    Graph G;
    initGraph(&G, N, E);
    int i, j;
    scanf("%d %d", &i, &j);
    int shortestPath = findShortestPath(&G, i, j);
    if (shortestPath == INT_MAX) {
        printf("There is no path between %d and %d.\n", i, j);
    } else {
        printf("The length of the shortest path between %d and %d is %d.\n", i, j, shortestPath);
    }
    return 0;
}

  • 26
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值