Initial commit

This commit is contained in:
xixu-me committed 2024-03-17 22:30:49 +08:00
commit bdf71aef37
120 files changed
+8284

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
// 数据结构定义
typedef struct
{
int num;
char name[20];
int score[3];
int ave;
} Student; // 结构体类型定义
// 函数声明
int menu_select();
void input(Student s[5]);
void output(Student s[5], int n);
void average(Student s[5]);
void sort(Student s[5]);
// 主函数
int main() {
Student stu[5]; // 准备实参
for (;;) {
switch (menu_select()) {
case 1:
printf("请输入5位同学的信息\n");
input(stu); // 函数调用
break;
case 2:
printf("输出5位同学的信息\n");
output(stu, 5);
break;
case 3:
average(stu);
printf("平均分已经求过\n");
break;
case 4:
sort(stu);
printf("按照平均分由高到低排序已经完成\n");
break;
case 5:
printf("输出前3名同学的信息\n");
sort(stu); // 输出前3名之前先排序
output(stu, 3);
break;
case 0:
printf("谢谢使用本软件\n");
exit(0);
}
}
return 0;
}
// 菜单函数
int menu_select() {
int sn;
printf("\n1.输入5位同学的信息\n");
printf("2.输出5位同学的信息\n");
printf("3.求平均分\n");
printf("4.排序\n");
printf("5.输出前三名\n");
printf("0.结束\n");
printf("Input 0~5:");
for (;;) {
scanf("%d", &sn);
if (sn < 0 || sn > 5)
printf("\n输入错误,重选0~5:");
else
break;
}
return sn;
}
// 输入函数
void input(Student s[5]) {
int i, j;
for (i = 0; i < 5; i++) {
scanf("%d", &s[i].num);
scanf("%s", s[i].name);
for (j = 0; j < 3; j++) {
scanf("%d", &s[i].score[j]);
}
}
}
// 输出函数
void output(Student s[5], int n) // 增加一个参数n,为输出元素的个数
{
int i, j;
for (i = 0; i < n; i++) {
printf("%d\t", s[i].num);
printf("%s\t", s[i].name);
for (j = 0; j < 3; j++) {
printf("%d\t", s[i].score[j]);
}
printf("%d\t", s[i].ave);
printf("\n");
}
}
// 求平均分
void average(Student s[5]) {
int i, j, sum;
for (i = 0; i < 5; i++) {
sum = 0;
for (j = 0; j < 3; j++) {
sum += s[i].score[j];
}
s[i].ave = sum / 3;
}
}
// 冒泡排序
void sort(Student s[5]) {
average(s); // 排序之前应该先求过平均分
int i, j;
Student t;
for (i = 4; i > 0; i--) {
for (j = 0; j < i; j++) {
if (s[j].ave < s[j + 1].ave) {
t = s[j];
s[j] = s[j + 1];
s[j + 1] = t;
}
}
}
}
@@ -0,0 +1,5 @@
111 aaa 88 88 88
222 bbb 66 66 66
333 ccc 99 99 99
444 ddd 55 55 55
555 fff 77 77 77
+206
View File
@@ -0,0 +1,206 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define LIST_INIT_SIZE 10 // 表存储空间的初始分配量
#define LISTINCREMENT 2 // 线性表存储空间的分配增量
// 数据结构
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType *elem; // 存储空间基址
int length; // 当前长度
int listsize; // 当前分配的存储容量(以sizeof(ElemType)为单位)
} SqList;
// 函数声明
int menu_select();
Status InitList_Sq(SqList &L);
Status CreatList_Sq(SqList &L, int n);
void PrintList_Sq(SqList L);
Status ListInsert_Sq(SqList &L, int i, ElemType e);
Status ListDelete_Sq(SqList &L, int i, ElemType &e);
int LocateElem_Sq(SqList L, ElemType e, Status (*compare)(ElemType, ElemType));
Status equal(ElemType x, ElemType y);
// 主函数
int main() {
SqList L;
Status s;
int n, i, e;
for (;;) {
switch (menu_select()) {
case 1:
s = InitList_Sq(L);
if (s)
printf("初始化成功\n");
else
printf("初始化失败\n");
break;
case 2:
printf("输入线性表的长度:");
scanf("%d", &n);
s = CreatList_Sq(L, n);
if (s)
printf("创建成功\n");
else
printf("创建失败\n");
break;
case 3:
PrintList_Sq(L);
break;
case 4:
printf("请输入插入的位序:");
scanf("%d", &i);
printf("请输入插入的新元素的值:");
scanf("%d", &e);
s = ListInsert_Sq(L, i, e);
if (s)
printf("插入成功!\n");
else
printf("插入失败!\n");
break;
case 5:
printf("输入删除的位序:");
scanf("%d", &i);
s = ListDelete_Sq(L, i, e);
if (s)
printf("删除了元素%d成功\n", e);
else
printf("删除失败\n");
break;
break;
case 6:
printf("请输入查找的元素的值:");
scanf("%d", &e);
i = LocateElem_Sq(L, e, equal); // 指向函数类型的指针作形参,实参用同类型的函数名equal
if (i)
printf("%d的逻辑位序是%d\n", e, i);
else
printf("查找失败!\n");
break;
case 0:
printf("程序结束,谢谢使用!\n\n");
exit(0);
}
}
return 0;
}
// 菜单函数
int menu_select() {
int sn;
printf("\n显示菜单\n");
printf("1.初始化\n");
printf("2.创建\n");
printf("3.显示\n");
printf("4.插入\n");
printf("5.删除\n");
printf("6.查找\n");
printf("0.退出\n");
printf("输入 0-6:");
for (;;) {
scanf("%d", &sn);
if (sn < 0 || sn > 6)
printf("\n输入错误,重选0-6:");
else
break;
}
return sn;
}
// 初始化空的动态顺序表函数
Status InitList_Sq(SqList &L) {
L.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem)
return (OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
// 创建动态顺序表(输入n个元素)
Status CreatList_Sq(SqList &L, int n) {
int i;
if (n > L.listsize)
return (ERROR);
printf("输入%d个整型数:", n);
for (i = 1; i <= n; i++) {
scanf("%d", &L.elem[i - 1]); // 类C代码中无格式输入字符串,需要补充
}
L.length = n;
return OK;
}
// 输出顺序表元素
void PrintList_Sq(SqList L) {
int i;
for (i = 1; i <= L.length; i++) {
printf("%d\t", L.elem[i - 1]);
}
printf("\n");
}
// 插入新元素e到第i个位序
Status ListInsert_Sq(SqList &L, int i, ElemType e) {
ElemType *newbase, *q, *p; // 类C代码中不含变量定义,需要补充
if (i < 1 || i > L.length + 1) // 插入位置不合法
return ERROR;
if (L.length >= L.listsize) // 当前储存空间不足
{
newbase = (ElemType *)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase)
exit(OVERFLOW); // 存储位置失败
L.elem = newbase; // 新基址
L.listsize += LISTINCREMENT; // 增加存储位置
}
q = &(L.elem[i - 1]); // 要插入的位置
for (p = &(L.elem[L.length - 1]); p >= q; --p)
*(p + 1) = *p; // 插入位置之后的元素右移
*q = e; // 插入e
++L.length;
return OK; // 表长增加1
} // ListInsert_Sq
// 删除第i个元素
Status ListDelete_Sq(SqList &L, int i, ElemType &e) {
ElemType *p, *q; // 补出变量定义
if ((i < 1) || (i > L.length))
return ERROR;
p = &(L.elem[i - 1]);
e = *p;
q = L.elem + L.length - 1;
e = *p;
q = L.elem + L.length - 1;
for (++p; p <= q; ++p)
*(p - 1) = *p;
--L.length;
return OK;
}
// 查找给定值的位序
int LocateElem_Sq(SqList L, ElemType e, Status (*compare)(ElemType, ElemType) /*指向函数类型的指针作形参*/) {
ElemType *p;
int i; // 补出变量定义
i = 1; // 当前元素的逻辑位序
p = L.elem; // 当前元素的物理地址
while (i <= L.length && !(*compare)(*(p++), e))
++i;
if (i <= L.length)
return i;
else
return 0;
} // LocateElem_Sq
// 判断两个数据元素是否相等的函数
Status equal(ElemType x, ElemType y) // 为LocateElem_Sq函数准备第三个实参
{
if (x == y)
return OK;
else
return ERROR;
}
+247
View File
@@ -0,0 +1,247 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
// 数据结构
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
} LNode, *LinkList;
// 函数声明
int menu_select();
int menu_select();
void CreateList_L(LinkList &L, int n);
void PrintList_L(LinkList L);
Status GetElem_L(LinkList &L, int i, ElemType &e);
Status ListInsert_L(LinkList &L, int i, ElemType e);
Status ListDelete_L(LinkList &L, int i, ElemType &e);
int LocateElem_L(LinkList L, ElemType e);
// 主函数
int main()
{
LinkList L;
int n, i, e, k;
for (;;)
{
switch (menu_select())
{
case 1:
printf("请输入元素的个数:");
scanf("%d", &n);
CreateList_L(L, n);
printf("创建完成\n");
break;
case 2:
PrintList_L(L);
break;
case 3:
printf("请输入要查找的元素的位序:");
scanf("%d", &i);
if (GetElem_L(L, i, e) == OK) // 调用取元素函数,如果成功,返回元素值给 e
{
printf("第%d个元素的值是%d\n", i, e);
}
else // 如果失败,输出错误信息
{
printf("查找失败,不存在第%d个元素\n", i);
}
break;
case 4:
printf("请输入要插入的元素的位序和值,用空格隔开:");
scanf("%d %d", &i, &e);
if (ListInsert_L(L, i, e) == OK) // 调用插入函数,如果成功,输出插入成功信息
{
printf("插入成功\n");
}
else // 如果失败,输出错误信息
{
printf("插入失败,插入位置不合法\n");
}
break;
case 5:
printf("请输入要删除的元素的位序:");
scanf("%d", &i);
if (ListDelete_L(L, i, e) == OK) // 调用删除函数,如果成功,返回删除的元素值给 e,并输出删除成功信息
{
printf("删除成功,删除的元素值是%d\n", e);
}
else // 如果失败,输出错误信息
{
printf("删除失败,删除位置不合法\n");
}
break;
case 6:
printf("请输入要查找的元素的值:");
scanf("%d", &e);
k = LocateElem_L(L, e); // 调用查找函数(已知元素找位序),返回位序给 k
if (k != 0) // 如果 k 不为 0,说明找到了元素 e,并输出其位序
{
printf("找到了元素%d,它的位序是%d\n", e, k);
}
else // 如果 k 为 0,说明没有找到元素 e,并输出查找失败信息
{
printf("查找失败,不存在元素%d\n", e);
}
break;
case 0:
printf("程序结束,谢谢使用!\n\n");
exit(0);
}
}
return 0;
}
int menu_select()
{
int sn;
printf("\n显示菜单\n");
printf("1.创建\n");
printf("2.显示\n");
printf("3.取元素\n");
printf("4.插入\n");
printf("5.删除\n");
printf("6.查找\n");
printf("0.退出\n");
printf("输入 0-6:");
for (;;)
{
scanf("%d", &sn);
if (sn < 0 || sn > 6)
printf("\n输入错误,重选0-6:");
else
break;
}
return sn;
}
// 创建单链表,头插法,已知线性表的长度
void CreateList_L(LinkList &L, int n)
{
LinkList p;
int i;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
printf("请逆序输入%d个元素:\n", n);
for (i = n; i >= 1; i--)
{
p = (LinkList)malloc(sizeof(LNode));
scanf("%d", &p->data); // 格式输入字符串补出来
p->next = L->next;
L->next = p;
}
}
// 输出单链表
void PrintList_L(LinkList L)
{
LinkList p;
p = L->next;
printf("输出链表中的元素:\n");
while (p)
{
printf("%d\t", p->data);
p = p->next;
}
printf("\n");
}
// 取元素函数
Status GetElem_L(LinkList &L, int i, ElemType &e)
{
// 在单链表 L 中查找第 i 个元素,并将其值赋给 e
LinkList p; // 定义一个指针 p
int j; // 定义一个计数器 j
p = L->next; // 让 p 指向链表 L 的第一个结点
j = 1; // 初始化 j 为 1
while (p && j < i) // p 不为空且计数器 j 还没有等于 i 时,循环继续
{
p = p->next; // 让 p 指向下一个结点
j++; // 让 j 增加 1
}
if (!p || j > i) // 如果 p 为空或者 j 大于 i,说明第 i 个元素不存在
{
return ERROR; // 返回错误标志
}
e = p->data; // 取出第 i 个元素的数据,赋给 e
return OK; // 返回成功标志
}
// 插入函数
Status ListInsert_L(LinkList &L, int i, ElemType e)
{
// 在单链表 L 中的第 i 个位置插入新的元素 e
LinkList p, s; // 定义两个指针 p 和 s
int j; // 定义一个计数器 j
p = L; // 让 p 指向链表 L 的头结点
j = 0; // 初始化 j 为 0
while (p && j < i - 1) // 寻找第 i-1 个结点,p 指向该结点
{
p = p->next;
j++;
}
if (!p || j > i - 1) // 如果 p 为空或者 j 大于 i-1,说明插入位置不合法
{
return ERROR; // 返回错误标志
}
s = (LinkList)malloc(sizeof(LNode)); // 分配一个新的结点 s
s->data = e; // 将新元素 e 赋给 s 的数据域
s->next = p->next; // 将 s 的指针域指向 p 的后继结点
p->next = s; // 将 p 的指针域指向 s 结点
return OK; // 返回成功标志
}
// 删除函数
Status ListDelete_L(LinkList &L, int i, ElemType &e)
{
// 在单链表 L 中删除第 i 个元素,并用 e 返回其值
LinkList p, q; // 定义两个指针 p 和 q
int j; // 定义一个计数器 j
p = L; // 让 p 指向链表 L 的头结点
j = 0; // 初始化 j 为 0
while (p->next && j < i - 1) // 寻找第 i-1 个结点,p 指向该结点,且保证 p 的后继不为空(即第 i 个结点存在)
{
p = p->next;
j++;
}
if (!(p->next) || j > i - 1) // 如果 p 的后继为空或者 j 大于 i-1,说明删除位置不合法
{
return ERROR; // 返回错误标志
}
q = p->next; // 让 q 指向要删除的结点(即第 i 个结点)
p->next = q->next; // 将 q 的后继赋给 p 的后继(即相当于断开了 q 结点)
e = q->data; // 将 q 结点的数据赋给 e(用于返回)
free(q); // 释放 q 结点的空间
return OK; // 返回成功标志
}
// 查找函数(已知元素找位序)
int LocateElem_L(LinkList L, ElemType e)
{
LinkList p;
int i;
p = L->next;
i = 1;
while (p && p->data != e) // 从第一个结点开始,遍历链表,直到找到元素 e 或者链表结束
{
p = p->next;
i++;
}
if (p) // 如果找到了元素 e,返回其位序 i
{
return i;
}
else // 如果没有找到元素 e,返回 0
{
return 0;
}
}
+175
View File
@@ -0,0 +1,175 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE 10 // 顺序栈存储空间的初始分配量
#define STACKINCREMENT 2 // 顺序栈存储空间的分配增量
// 输出顺序栈的元素
void PrintStack(SqStack S) {
SElemType *p;
for (p = S.base; p < S.top; p++) {
printf("%d\t", *p);
}
}
// 输入n个元素入栈
Status CreateStack(SqStack &S, int n) {
int i;
if (n > S.stacksize)
return (ERROR);
printf("输入%d个整型数:", n);
for (i = 1; i <= n; i++) {
scanf("%d", S.top++);
}
return OK;
}
// 菜单函数
int menu_select() {
int sn;
printf("\n显示菜单\n");
printf("1.初始化栈\n");
printf("2.创建栈\n");
printf("3.显示栈\n");
printf("4.取栈顶元素\n");
printf("5.入栈\n");
printf("6.出栈\n");
printf("7.判断栈空否\n");
printf("8.销毁栈\n");
printf("9.数制转换\n");
// printf("10.括号匹配\n");
printf("0.退出\n");
printf("输入 0-8:");
for (;;) {
scanf("%d", &sn);
if (sn < 0 || sn > 9)
printf("\n输入错误,重选0-8:");
else
break;
}
return sn;
}
void Conversion() {
SqStack S;
InitStack(S);
int N;
printf("输入要转换的十进制数:");
scanf("%d", &N);
while (N) {
Push(S, N % 8);
N /= 8;
}
printf("转换后的八进制数为:");
while (!StackEmpty(S)) {
int e;
Pop(S, e);
printf("%d", e);
}
printf("\n");
}
// void BracketMatch() {
// SqStack S;
// InitStack(S);
// char c;
// printf("输入括号序列:");
// while ((c = getchar()) != '\n') {
// if (c == '(')
// Push(S, c);
// else if (c == ')') {
// if (StackEmpty(S)) {
// printf("括号不匹配\n");
// return;
// }
// Pop(S, c);
// }
// }
// if (StackEmpty(S))
// printf("括号匹配\n");
// else
// printf("括号不匹配\n");
// }
// 主函数
int main() {
SqStack S;
Status s;
int n;
SElemType e;
for (;;) {
switch (menu_select()) {
case 1:
s = InitStack(S);
if (s)
printf("初始化成功\n");
else
printf("初始化失败\n");
break;
case 2:
printf("输入栈的长度:");
scanf("%d", &n);
s = CreateStack(S, n);
if (s)
printf("创建成功\n");
else
printf("创建失败\n");
break;
case 3:
PrintStack(S);
break;
case 4:
s = GetTop(S, e);
if (s)
printf("栈顶元素为%d\n", e);
else
printf("栈为空,取栈顶元素失败\n");
break;
case 5:
printf("输入入栈的元素值:");
scanf("%d", &e);
s = Push(S, e);
if (s)
printf("%d入栈成功\n", e);
else
printf("入栈失败\n");
break;
case 6:
s = Pop(S, e);
if (s)
printf("%d出栈成功\n", e);
else
printf("栈为空,出栈失败\n");
break;
case 7:
s = StackEmpty(S);
if (s)
printf("栈为空\n");
else
printf("栈不为空\n");
break;
case 8:
s = DestroyStack(S);
if (s)
printf("销毁栈成功\n");
else
printf("销毁栈失败\n");
break;
case 9:
Conversion();
break;
// case 10:
// BracketMatch();
// break;
case 0:
printf("程序结束,谢谢使用\n\n");
exit(0);
}
}
return 0;
}
@@ -0,0 +1,74 @@
// 预编译命令
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE 10 // 顺序栈存储空间的初始分配量
#define STACKINCREMENT 2 // 顺序栈存储空间的分配增量
// 数据结构
typedef int Status;
typedef int SElemType; // 完成数制转换
// typedef char SElemType; //完成括号匹配
typedef struct {
SElemType *base; // 存储空间基址
SElemType *top; // 存储空间基址
int stacksize; // 当前分配的存储容量(以sizeof(ElemType)为单位)
} SqStack;
// 构造一个最大空间为 STACK_INIT_SIZE的空顺序栈S
Status InitStack(SqStack &S) {
S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if (!S.base)
exit(OVERFLOW); // 存储分配失败
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
// 栈不空,则用e返回栈顶元素
Status GetTop(SqStack S, SElemType &e) {
if (S.top == S.base)
return ERROR;
e = *(S.top - 1);
return OK;
}
// 给定值e入栈
Status Push(SqStack &S, SElemType e) {
if (S.top - S.base >= S.stacksize) {
S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return OK;
}
// 若栈不空,则删除S的栈顶元素,
// 用 e 返回其值,并返回OK;
// 否则返回ERROR
Status Pop(SqStack &S, SElemType &e) {
if (S.top == S.base)
return ERROR;
e = *--S.top;
return OK;
}
// 判断栈空否
Status StackEmpty(SqStack S) {
if (S.top == S.base)
return OK;
else
return ERROR;
}
// 销毁栈
Status DestroyStack(SqStack &S) {
if (!S.base)
return ERROR;
free(S.base);
return OK;
}
@@ -0,0 +1,95 @@
#include <stdio.h>
#define MAXSIZE 50
typedef struct
{
int data[MAXSIZE];
int size;
} seqlist;
void seqlist_init(seqlist *list) {
list->size = 0;
}
void insert(seqlist *list, int position, int data) {
if (list->size == MAXSIZE) {
printf("seqlist is full\n");
return;
}
if (position < 0 || position > list->size) {
printf("position is out of range\n");
return;
}
for (int i = list->size - 1; i >= position; i--) {
list->data[i + 1] = list->data[i];
}
list->data[position] = data;
list->size++;
}
void delete(seqlist *list, int position) {
if (list->size == MAXSIZE) {
printf("seqlist is full\n");
return;
}
if (position < 0 || position >= list->size) {
printf("position is out of range\n");
return;
}
for (int i = position; i <= list->size - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->size--;
}
int get(seqlist *list, int position) {
if (position < 0 || position >= list->size) {
printf("获取位置不合法\n");
return -1; // 返回一个特殊值表示错误
}
return list->data[position];
}
int search(seqlist *list, int data) {
for (int i = 0; i < list->size; i++) {
if (list->data[i] == data)
return i;
}
return -1;
}
void printSeqList(seqlist *list) {
printf("顺序表元素: ");
for (int i = 0; i < list->size; i++) {
printf("%d ", list->data[i]);
}
printf("\n");
}
int main() {
seqlist myList;
seqlist_init(&myList);
insert(&myList, 0, 1);
insert(&myList, 1, 2);
insert(&myList, 2, 3);
printSeqList(&myList);
delete (&myList, 1);
printSeqList(&myList);
int value = get(&myList, 1);
if (value != -1) {
printf("位置1的元素为: %d\n", value);
}
int position = search(&myList, 3);
if (position != -1) {
printf("元素3的位置为: %d\n", position);
}
return 0;
}
@@ -0,0 +1,185 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *creat_front(int num[], int lenth) {
Node *head = NULL;
for (int i = 0; i < lenth; i++) {
Node *new_node = (Node *)malloc(sizeof(Node));
if (new_node == NULL) {
printf("Failed to allocate\n");
exit(1);
}
new_node->data = num[i];
new_node->next = head;
head = new_node;
}
return head;
}
Node *creat_back(int num[], int lenth) {
Node *head = NULL;
Node *back = NULL;
for (int i = 0; i < lenth; i++) {
Node *new_node = (Node *)malloc(sizeof(Node));
if (new_node == NULL) {
printf("Failed to allocate\n");
exit(1);
}
new_node->data = num[i];
new_node->next = NULL;
if (head == NULL) {
head = new_node;
back = new_node;
}
else {
back->next = new_node;
back = new_node;
}
}
return head;
}
int get_list(Node *head, int position) {
Node *q = head;
int i = 0;
while (q != NULL) {
if (i == position) {
return q->data;
}
else {
q = q->next;
i++;
}
}
if (q == NULL)
printf("position is out of range and fail to get data!\n");
free(q);
return -1;
}
Node *insert(Node *head, int position, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
printf("fail to allocate!\n");
exit(1);
}
newNode->data = data;
if (position == 0) {
newNode->next = head;
head = newNode;
}
else {
Node *current = head;
int index = 0;
while (current != NULL && index < position - 1) {
current = current->next;
index++;
}
if (current != NULL) {
newNode->next = current->next;
current->next = newNode;
}
else {
printf("插入位置不合法\n");
free(newNode);
}
}
return head;
}
int findElement(Node *head, int value) {
Node *current = head;
int i = 0;
while (current != NULL) {
if (current->data == value) {
return i;
}
current = current->next;
i++;
}
exit(i);
}
Node *deleteElement(Node *head, int position) {
if (head == NULL) {
printf("链表为空\n");
return NULL;
}
Node *temp;
if (position == 0) {
temp = head;
head = head->next;
}
else {
Node *current = head;
int index = 0;
while (current != NULL && index < position - 1) {
current = current->next;
index++;
}
if (current != NULL && current->next != NULL) {
temp = current->next;
current->next = current->next->next;
}
else {
printf("删除位置不合法\n");
return head;
}
}
free(temp);
return head;
}
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
int a[] = { 5, 6, 8, 9, 1 };
Node *myList = creat_front(a, 5);
printf("List after front insertion: ");
printList(myList);
free(myList);
myList = creat_back(a, 5);
printf("List after end insertion: ");
printList(myList);
int valueAtIndex2 = get_list(myList, 2);
printf("Value at index 2: %d\n", valueAtIndex2);
int searchResult = findElement(myList, 8);
printf("Index of value 8: %d\n", searchResult);
myList = insert(myList, 2, 10);
printf("List after insertion at index 2: ");
printList(myList);
myList = deleteElement(myList, 3);
printf("List after deletion at index 3: ");
printList(myList);
free(myList);
return 0;
}
@@ -0,0 +1,84 @@
#include <stdio.h>
// 定义多项式的项
typedef struct
{
int coefficient; // 系数
int exponent; // 指数
} Term;
// 函数声明
void addPolynomials(Term poly1[], int n1, Term poly2[], int n2, Term result[], int *nResult);
int main() {
int n1, n2;
// 输入第一个多项式的项数
printf("第一个多项式\n项数:");
scanf("%d", &n1);
// 输入第一个多项式的各项系数和指数
Term poly1[n1];
for (int i = 0; i < n1; i++) {
printf("第%d项系数和指数:", i + 1);
scanf("%d %d", &poly1[i].coefficient, &poly1[i].exponent);
}
// 输入第二个多项式的项数
printf("\n第二个多项式\n项数:");
scanf("%d", &n2);
// 输入第二个多项式的各项系数和指数
Term poly2[n2];
for (int i = 0; i < n2; i++) {
printf("第%d项系数和指数:", i + 1);
scanf("%d %d", &poly2[i].coefficient, &poly2[i].exponent);
}
// 计算两个多项式的和
int nResult = n1 + n2;
Term result[nResult];
addPolynomials(poly1, n1, poly2, n2, result, &nResult);
// 输出结果
printf("\n和多项式的各项为:\n");
for (int i = 0; i < nResult; i++) {
printf("第%d项,系数:%d,指数:%d\n", i + 1, result[i].coefficient, result[i].exponent);
}
return 0;
}
// 实现多项式相加的函数
void addPolynomials(Term poly1[], int n1, Term poly2[], int n2, Term result[], int *nResult) {
int i = 0, j = 0, k = 0;
// 循环遍历两个多项式的项
while (i < n1 && j < n2) {
// 比较当前项的指数大小
if (poly1[i].exponent > poly2[j].exponent) {
result[k++] = poly1[i++];
}
else if (poly1[i].exponent < poly2[j].exponent) {
result[k++] = poly2[j++];
}
else {
// 指数相等时,系数相加
result[k].exponent = poly1[i].exponent;
result[k++].coefficient = poly1[i++].coefficient + poly2[j++].coefficient;
}
}
// 处理多项式1剩余的项
while (i < n1) {
result[k++] = poly1[i++];
}
// 处理多项式2剩余的项
while (j < n2) {
result[k++] = poly2[j++];
}
// 更新结果多项式的项数
*nResult = k;
}
@@ -0,0 +1,193 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 学生结构体
typedef struct
{
int id;
char name[5];
} Student;
// 链表节点结构体
typedef struct Node {
Student student;
struct Node *next;
} Node;
// 链表结构体
typedef struct
{
Node *head;
} LinkedList;
// 函数声明
void initList(LinkedList *list);
void insertStudent(LinkedList *list, Student student);
void printList(LinkedList list);
Node *findStudentById(LinkedList list, int id);
void deleteStudentById(LinkedList *list, int id);
void clearList(LinkedList *list);
int main() {
LinkedList studentList;
initList(&studentList);
int choice;
do {
// 用户菜单
printf("\n学生管理系统菜单:\n");
printf("1. 添加学生\n");
printf("2. 删除学生\n");
printf("3. 查找学生\n");
printf("4. 打印学生列表\n");
printf("5. 清空学生列表\n");
printf("6. 退出\n");
printf("请选择操作(1-6): ");
scanf("%d", &choice);
switch (choice) {
case 1: {
// 添加学生
Student newStudent;
printf("请输入学号(1-100): ");
scanf("%d", &newStudent.id);
printf("请输入姓名(不超过4个字符): ");
scanf("%s", newStudent.name);
insertStudent(&studentList, newStudent);
break;
}
case 2: {
// 删除学生
int id;
printf("请输入要删除学生的学号: ");
scanf("%d", &id);
deleteStudentById(&studentList, id);
break;
}
case 3: {
// 查找学生
int id;
printf("请输入要查找学生的学号: ");
scanf("%d", &id);
Node *foundStudent = findStudentById(studentList, id);
if (foundStudent != NULL) {
printf("找到学生:学号 %d,姓名 %s\n", foundStudent->student.id, foundStudent->student.name);
}
else {
printf("未找到学生。\n");
}
break;
}
case 4:
// 打印学生列表
printList(studentList);
break;
case 5:
// 清空学生列表
clearList(&studentList);
printf("学生列表已清空。\n");
break;
case 6:
// 退出程序
printf("程序已退出。\n");
break;
default:
printf("无效的选择,请重新输入。\n");
}
} while (choice != 6);
return 0;
}
// 初始化链表
void initList(LinkedList *list) {
list->head = NULL;
}
// 在有序链表中插入学生
void insertStudent(LinkedList *list, Student student) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->student = student;
newNode->next = NULL;
if (list->head == NULL || student.id < list->head->student.id) {
// 插入头部
newNode->next = list->head;
list->head = newNode;
}
else {
// 插入中间或尾部
Node *current = list->head;
while (current->next != NULL && student.id > current->next->student.id) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
printf("学生已添加:学号 %d,姓名 %s\n", student.id, student.name);
}
// 打印学生列表
void printList(LinkedList list) {
Node *current = list.head;
printf("\n学生列表:\n");
while (current != NULL) {
printf("学号 %d,姓名 %s\n", current->student.id, current->student.name);
current = current->next;
}
}
// 根据学号查找学生
Node *findStudentById(LinkedList list, int id) {
Node *current = list.head;
while (current != NULL) {
if (current->student.id == id) {
return current;
}
current = current->next;
}
return NULL;
}
// 根据学号删除学生
void deleteStudentById(LinkedList *list, int id) {
Node *current = list->head;
Node *prev = NULL;
while (current != NULL && current->student.id != id) {
prev = current;
current = current->next;
}
if (current != NULL) {
// 找到学生,进行删除操作
if (prev == NULL) {
// 删除头节点
list->head = current->next;
}
else {
prev->next = current->next;
}
free(current);
printf("学生已删除:学号 %d\n", id);
}
else {
printf("未找到学生。\n");
}
}
// 清空学生列表
void clearList(LinkedList *list) {
Node *current = list->head;
while (current != NULL) {
Node *next = current->next;
free(current);
current = next;
}
list->head = NULL;
}
@@ -0,0 +1,106 @@
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
char data;
TreeNode *left;
TreeNode *right;
};
// 创建二叉树
TreeNode *create() {
char ch;
cin >> ch;
if (ch == '#')
return nullptr;
TreeNode *node = new TreeNode();
node->data = ch;
node->left = create();
node->right = create();
return node;
}
// 销毁二叉树
void destroy(TreeNode *root) {
if (root == nullptr)
return;
destroy(root->left);
destroy(root->right);
delete root;
}
// 先序遍历
void preOrder(TreeNode *root) {
if (root == nullptr)
return;
cout << root->data << ' ';
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode *root) {
if (root == nullptr)
return;
inOrder(root->left);
cout << root->data << ' ';
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode *root) {
if (root == nullptr)
return;
postOrder(root->left);
postOrder(root->right);
cout << root->data << ' ';
}
// 层次遍历
void levelOrder(TreeNode *root) {
if (root == nullptr)
return;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
TreeNode *node = q.front();
q.pop();
cout << node->data << ' ';
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
}
// 用括号表示法输出二叉树
void printWithBrackets(TreeNode *root) {
if (root == nullptr)
return;
cout << root->data;
if (root->left || root->right) {
cout << '(';
printWithBrackets(root->left);
cout << ',';
printWithBrackets(root->right);
cout << ')';
}
}
int main() {
TreeNode *root = create();
preOrder(root);
cout << endl;
inOrder(root);
cout << endl;
postOrder(root);
cout << endl;
levelOrder(root);
cout << endl;
printWithBrackets(root);
cout << endl;
destroy(root);
return 0;
}
@@ -0,0 +1,80 @@
#include <iostream>
using namespace std;
// 定义线索二叉树节点
struct Node {
int data;
Node *left, *right;
int ltag, rtag; // 左右标志位,0表示指向子节点,1表示指向前驱或后继
};
Node *pre = NULL; // 全局变量,记录上一个访问的节点
// 创建线索二叉树
Node *createTree(int data) {
Node *node = new Node();
node->data = data;
node->left = node->right = NULL;
node->ltag = node->rtag = 0;
return node;
}
// 中序遍历线索化
void inThreading(Node *node) {
if (node) {
inThreading(node->left); // 递归左子树
if (!node->left) { // 如果该节点没有左孩子,设置ltag为1,并让left指向上一个节点
node->ltag = 1;
node->left = pre;
}
if (pre && !pre->right) { // 如果上一个节点没有右孩子,设置rtag为1,并让right指向当前节点
pre->rtag = 1;
pre->right = node;
}
pre = node;
inThreading(node->right); // 递归右子树
}
}
// 中序遍历线索二叉树
void inOrder(Node *node) {
while (node) {
while (!node->ltag) // 如果ltag为0,一直找到最左下节点
node = node->left;
cout << node->data << " ";
while (node->rtag) { // 如果rtag为1,一直找到最右下节点
node = node->right;
cout << node->data << " ";
}
node = node->right; // 转向右子树
}
}
// 查找节点的前驱
Node *findPredecessor(Node *node) {
if (node->ltag) // 如果ltag为1,left指向的就是前驱
return node->left;
else
return NULL;
}
// 查找节点的后继
Node *findSuccessor(Node *node) {
if (node->rtag) // 如果rtag为1,right指向的就是后继
return node->right;
else
return NULL;
}
// 主函数
int main() {
Node *root = createTree(1);
root->left = createTree(2);
root->right = createTree(3);
root->left->left = createTree(4);
root->left->right = createTree(5);
inThreading(root);
inOrder(root);
return 0;
}
@@ -0,0 +1,64 @@
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct Node {
int weight;
string code;
Node *left, *right;
Node(int w) : weight(w), left(NULL), right(NULL) {}
};
struct cmp {
bool operator()(Node *a, Node *b) {
return a->weight > b->weight;
}
};
void generateHuffmanCode(Node *root, string str) {
if (!root)
return;
if (!root->left && !root->right) {
root->code = str;
}
generateHuffmanCode(root->left, str + "0");
generateHuffmanCode(root->right, str + "1");
}
int main() {
int n;
cin >> n;
priority_queue<Node *, vector<Node *>, cmp> pq;
for (int i = 0; i < n; ++i) {
int w;
cin >> w;
pq.push(new Node(w));
}
while (pq.size() != 1) {
Node *left = pq.top();
pq.pop();
Node *right = pq.top();
pq.pop();
Node *parent = new Node(left->weight + right->weight);
parent->left = left;
parent->right = right;
pq.push(parent);
}
generateHuffmanCode(pq.top(), "");
vector<Node *> nodes;
nodes.push_back(pq.top());
while (!nodes.empty()) {
Node *node = nodes.back();
nodes.pop_back();
if (node->left)
nodes.push_back(node->left);
if (node->right)
nodes.push_back(node->right);
if (!node->left && !node->right) {
cout << node->code << " ";
}
}
return 0;
}
@@ -0,0 +1,59 @@
#include <iostream>
#include <map>
using namespace std;
class Node {
public:
string name;
map<string, Node *> children;
Node(string name) : name(name) {}
Node *find(string path) {
if (path.empty())
return this;
int pos = path.find('/');
string first = pos == string::npos ? path : path.substr(0, pos);
string rest = pos == string::npos ? "" : path.substr(pos + 1);
if (children.count(first) == 0)
return nullptr;
return children[first]->find(rest);
}
void add(string path) {
int pos = path.find('/');
string first = pos == string::npos ? path : path.substr(0, pos);
string rest = pos == string::npos ? "" : path.substr(pos + 1);
if (children.count(first) == 0)
children[first] = new Node(first);
if (!rest.empty())
children[first]->add(rest);
}
bool remove(string path) {
int pos = path.find('/');
string first = pos == string::npos ? path : path.substr(0, pos);
string rest = pos == string::npos ? "" : path.substr(pos + 1);
if (children.count(first) == 0)
return false;
if (rest.empty()) {
delete children[first];
children.erase(first);
return true;
}
return children[first]->remove(rest);
}
};
int main() {
Node root("/");
root.add("dir1/dir2/file");
cout << (root.find("dir1/dir2/file") != nullptr) << endl;
cout << (root.find("dir1/dir2") != nullptr) << endl;
cout << (root.find("dir1") != nullptr) << endl;
cout << (root.find("dir1/dir3") == nullptr) << endl;
root.remove("dir1/dir2/file");
cout << (root.find("dir1/dir2/file") == nullptr) << endl;
return 0;
}
@@ -0,0 +1,69 @@
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
// 图的邻接矩阵存储
vector<vector<int>> adjMatrix;
// 图的邻接表存储
vector<vector<int>> adjList;
// 图的深度优先遍历
void DFS(int start, vector<bool> &visited) {
stack<int> s;
s.push(start);
visited[start] = true;
while (!s.empty()) {
int vertex = s.top();
s.pop();
cout << vertex << " ";
for (int i = 0; i < adjList[vertex].size(); i++) {
if (!visited[adjList[vertex][i]]) {
s.push(adjList[vertex][i]);
visited[adjList[vertex][i]] = true;
}
}
}
}
// 图的广度优先遍历
void BFS(int start, vector<bool> &visited) {
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int vertex = q.front();
q.pop();
cout << vertex << " ";
for (int i = 0; i < adjList[vertex].size(); i++) {
if (!visited[adjList[vertex][i]]) {
q.push(adjList[vertex][i]);
visited[adjList[vertex][i]] = true;
}
}
}
}
int main() {
int n, m;
cin >> n >> m; // 输入顶点数和边数
adjMatrix.resize(n, vector<int>(n, 0));
adjList.resize(n);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v; // 输入边的两个顶点
adjMatrix[u][v] = 1;
adjMatrix[v][u] = 1;
adjList[u].push_back(v);
adjList[v].push_back(u);
}
vector<bool> visited(n, false);
DFS(0, visited); // 从顶点0开始深度优先遍历
cout << endl;
fill(visited.begin(), visited.end(), false);
BFS(0, visited); // 从顶点0开始广度优先遍历
return 0;
}
@@ -0,0 +1,92 @@
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX = 1e9;
const int N = 6;
double graph[N][N] = {
{ 0, 0.6, 0.1, 0.5, 0, 0 },
{ 0.6, 0, 0.5, 0, 0.3, 0 },
{ 0.1, 0.5, 0, 0.5, 0.6, 0.4 },
{ 0.5, 0, 0.5, 0, 0, 0.2 },
{ 0, 0.3, 0.6, 0, 0, 0.6 },
{ 0, 0, 0.4, 0.2, 0.6, 0 }
};
// Prim's Algorithm
void prim() {
vector<bool> selected(N, false);
vector<double> minWeight(N, MAX);
minWeight[0] = 0;
for (int i = 0; i < N; ++i) {
int u = -1;
for (int j = 0; j < N; ++j) {
if (!selected[j] && (u == -1 || minWeight[j] < minWeight[u])) {
u = j;
}
}
selected[u] = true;
for (int v = 0; v < N; ++v) {
if (!selected[v] && graph[u][v] != 0 && graph[u][v] < minWeight[v]) {
minWeight[v] = graph[u][v];
}
}
}
double totalWeight = 0;
for (int i = 0; i < N; ++i) {
totalWeight += minWeight[i];
}
cout << "Minimum cost with Prim's Algorithm: " << totalWeight << endl;
}
// Kruskal's Algorithm
struct Edge {
int u, v;
double weight;
bool operator<(const Edge &other) const {
return weight < other.weight;
}
};
int parent[N];
int find(int x) {
if (x != parent[x]) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void unionSet(int x, int y) {
parent[find(x)] = find(y);
}
void kruskal() {
vector<Edge> edges;
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
if (graph[i][j] > 0) {
edges.push_back({ i, j, graph[i][j] });
}
}
}
sort(edges.begin(), edges.end());
for (int i = 0; i < N; ++i) {
parent[i] = i;
}
double totalWeight = 0;
for (const Edge &edge : edges) {
if (find(edge.u) != find(edge.v)) {
totalWeight += edge.weight;
unionSet(edge.u, edge.v);
}
}
cout << "Minimum cost with Kruskal's Algorithm: " << totalWeight << endl;
}
int main() {
prim();
kruskal();
return 0;
}
@@ -0,0 +1,139 @@
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// 定义课程结构体,包含课程号,学分,入度,邻接表
struct Course {
string id; // 课程号
int credit; // 学分
int indegree; // 入度
vector<int> adj; // 邻接表
Course(string i, int c) : id(i), credit(c), indegree(0) {} // 构造函数
};
// 定义拓扑排序函数,参数为课程数组,学期总数,每学期学分上限,课程总数
void topologicalSort(vector<Course> &courses, int term, int limit, int num) {
queue<int> q; // 定义一个队列,用于存放入度为0的课程
vector<int> result; // 定义一个数组,用于存放拓扑排序的结果
int count = 0; // 定义一个计数器,用于记录已经安排的课程数
// 遍历课程数组,将入度为0的课程入队,并输出
for (int i = 0; i < num; i++) {
if (courses[i].indegree == 0)
q.push(i);
}
// 当队列不为空时,循环执行以下操作
while (!q.empty()) {
int u = q.front(); // 取出队首元素
q.pop(); // 出队
result.push_back(u); // 将队首元素加入结果数组
count++; // 计数器加一
// 遍历队首元素的邻接表,将其邻接课程的入度减一,如果入度变为0,则入队
for (int v : courses[u].adj) {
courses[v].indegree--;
if (courses[v].indegree == 0) {
q.push(v);
}
}
}
// 如果计数器等于课程总数,说明拓扑排序成功,否则说明有环,无法完成所有课程
if (count == num) {
cout << "拓扑排序成功,结果为:" << endl;
// 输出拓扑排序结果
for (int i = 0; i < num; i++) {
cout << courses[result[i]].id << " ";
}
cout << endl;
// 定义一个二维数组,用于存放每个学期的课程安排
vector<vector<int>> plan(term);
// 定义一个变量,用于记录当前安排到哪个学期
int current = 0;
// 定义一个变量,用于记录当前学期的已安排学分
int credit = 0;
// 遍历拓扑排序结果,按照策略安排课程
for (int i = 0; i < num; i++) {
// 如果当前课程的学分加上已安排学分超过学分上限,或者当前学期已满,则安排到下一个学期
if (credit + courses[result[i]].credit > limit || plan[current].size() == term) {
current++;
credit = 0;
}
// 如果当前学期还有空余,且没有超过学分上限,则安排当前课程到当前学期
if (current < term && credit + courses[result[i]].credit <= limit) {
plan[current].push_back(result[i]);
credit += courses[result[i]].credit;
}
}
// 输出每个学期的课程安排
cout << "按照给定的条件,最少需要" << current + 1 << "个学期完成所有课程,具体安排如下:" << endl;
for (int i = 0; i <= current; i++) {
cout << "第" << i + 1 << "个学期的课程有:";
for (int j = 0; j < plan[i].size(); j++) {
cout << courses[plan[i][j]].id << " ";
}
cout << endl;
}
}
else {
cout << "拓扑排序失败,无法完成所有课程的学习" << endl;
}
}
// 定义主函数,用于测试代码的功能
int main() {
// 定义课程总数,学期总数,每学期学分上限
int num, term, limit;
// 从标准输入读取这些参数
cout << "请输入学期总数,每学期学分上限,课程总数,用空格隔开:" << endl;
cin >> term >> limit >> num;
// 定义一个课程数组,用于存放课程信息
vector<Course> courses;
// 初始化课程信息,根据题目给定的数据
courses.push_back(Course("C1", 2));
courses.push_back(Course("C2", 3));
courses.push_back(Course("C3", 4));
courses.push_back(Course("C4", 3));
courses.push_back(Course("C5", 2));
courses.push_back(Course("C6", 3));
courses.push_back(Course("C7", 4));
courses.push_back(Course("C8", 4));
courses.push_back(Course("C9", 5));
courses.push_back(Course("C10", 3));
courses.push_back(Course("C11", 2));
courses.push_back(Course("C12", 5));
courses.push_back(Course("C13", 3));
courses.push_back(Course("C14", 3));
// 初始化课程之间的先修关系,根据题目给定的数据
courses[0].adj.push_back(1); // C1 -> C2
courses[0].adj.push_back(2); // C1 -> C3
courses[0].adj.push_back(3); // C1 -> C4
courses[0].adj.push_back(11); // C1 -> C12
courses[0].adj.push_back(13); // C1 -> C14
courses[1].adj.push_back(2); // C2 -> C3
courses[2].adj.push_back(4); // C3 -> C5
courses[2].adj.push_back(6); // C3 -> C7
courses[2].adj.push_back(7); // C3 -> C8
courses[3].adj.push_back(4); // C4 -> C5
courses[3].adj.push_back(12); // C4 -> C13
courses[4].adj.push_back(6); // C5 -> C7
courses[5].adj.push_back(7); // C6 -> C8
courses[5].adj.push_back(12); // C6 -> C13
courses[5].adj.push_back(13); // C6 -> C14
courses[8].adj.push_back(5); // C9 -> C6
courses[8].adj.push_back(9); // C9 -> C10
courses[8].adj.push_back(10); // C9 -> C11
courses[8].adj.push_back(11); // C9 -> C12
courses[9].adj.push_back(11); // C10 -> C12
courses[10].adj.push_back(5); // C11 -> C6
courses[10].adj.push_back(13); // C11 -> C14
courses[12].adj.push_back(13); // C13 -> C14
// 更新每个课程的入度
for (int i = 0; i < num; i++) {
for (int j : courses[i].adj) {
courses[j].indegree++;
}
}
// 调用拓扑排序函数,输出结果
topologicalSort(courses, term, limit, num);
return 0;
}
@@ -0,0 +1,64 @@
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
#define INF INT_MAX
#define N 6
void Dijkstra(int graph[N][N], int start) {
vector<int> dist(N, INF);
dist[start] = 0;
vector<bool> visited(N, false);
vector<int> prev(N, -1);
for (int count = 0; count < N - 1; count++) {
int min = INF, min_index;
for (int v = 0; v < N; v++)
if (!visited[v] && dist[v] <= min)
min = dist[v], min_index = v;
int u = min_index;
visited[u] = true;
for (int v = 0; v < N; v++)
if (!visited[v] && graph[u][v] && dist[u] != INF && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
prev[v] = u;
}
}
for (int i = 0; i < N; i++) {
if (i != start) {
cout << "Path from " << start << " to " << i << ": ";
if (dist[i] == INF) {
cout << "No path\n";
}
else {
vector<int> path;
for (int j = i; j != -1; j = prev[j])
path.push_back(j);
for (int j = path.size() - 1; j > 0; j--)
cout << path[j] << " -> ";
cout << path[0] << " (Cost: " << dist[i] << ")\n";
}
}
}
}
int main() {
int graph[N][N] = {
{ 0, 0, 10, 0, 30, 100 },
{ 0, 0, 5, 0, 0, 0 },
{ 0, 0, 0, 50, 0, 0 },
{ 0, 0, 0, 0, 0, 10 },
{ 0, 0, 0, 20, 0, 60 },
{ 0, 0, 0, 0, 0, 0 }
};
for (int i = 0; i < N; i++)
Dijkstra(graph, i);
return 0;
}
@@ -0,0 +1,109 @@
#include <iostream>
#include <limits>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 插入节点
TreeNode *insertNode(TreeNode *root, int val) {
if (root == NULL) {
return new TreeNode(val);
}
if (val < root->val) {
root->left = insertNode(root->left, val);
}
else if (val > root->val) {
root->right = insertNode(root->right, val);
}
return root;
}
// 删除节点
TreeNode *deleteNode(TreeNode *root, int key) {
if (root == NULL)
return root;
if (key < root->val) {
root->left = deleteNode(root->left, key);
}
else if (key > root->val) {
root->right = deleteNode(root->right, key);
}
else {
if (root->left == NULL) {
TreeNode *temp = root->right;
delete root;
return temp;
}
else if (root->right == NULL) {
TreeNode *temp = root->left;
delete root;
return temp;
}
TreeNode *temp = root->right;
while (temp && temp->left != NULL)
temp = temp->left;
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
return root;
}
// 判断是否为二叉搜索树
bool isValidBST(TreeNode *root, TreeNode *minNode = NULL, TreeNode *maxNode = NULL) {
if (root == NULL)
return true;
if (minNode != NULL && root->val <= minNode->val || maxNode != NULL && root->val >= maxNode->val) {
return false;
}
return isValidBST(root->left, minNode, root) && isValidBST(root->right, root, maxNode);
}
// 查找最大值和第二大值
pair<int, int> findMaxAndSecondMax(TreeNode *root) {
int maxVal = numeric_limits<int>::min();
int secondMaxVal = numeric_limits<int>::min();
TreeNode *curr = root;
while (curr) {
if (curr->val > maxVal) {
secondMaxVal = maxVal;
maxVal = curr->val;
}
else if (curr->val > secondMaxVal && curr->val < maxVal) {
secondMaxVal = curr->val;
}
curr = curr->right;
}
return { maxVal, secondMaxVal };
}
// 主函数,用于测试以上所有功能
int main() {
int n;
TreeNode *root = NULL;
cout << "Enter a number to insert: ";
while (true) {
int val;
cin >> val;
if (val == -1)
break;
root = insertNode(root, val);
}
cout << "Is valid BST: " << (isValidBST(root) ? "Yes" : "No") << endl;
auto maxAndSecondMax = findMaxAndSecondMax(root);
cout << "Max: " << maxAndSecondMax.first << ", Second Max: " << maxAndSecondMax.second << endl;
cout << "Enter a number to delete: ";
cin >> n;
root = deleteNode(root, n);
cout << "After deleting " << n << ", is valid BST: " << (isValidBST(root) ? "Yes" : "No") << endl;
return 0;
}
@@ -0,0 +1,123 @@
#include <iostream>
using namespace std;
struct Node {
int key;
Node *left;
Node *right;
int height;
};
Node *newNode(int key) {
Node *node = new Node();
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return (node);
}
int height(Node *N) {
if (N == NULL)
return 0;
return N->height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
Node *rightRotate(Node *y) {
Node *x = y->left;
Node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
Node *leftRotate(Node *x) {
Node *y = x->right;
Node *T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
int getBalance(Node *N) {
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
Node *insert(Node *node, int key) {
if (node == NULL)
return (newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
else
return node;
node->height = 1 + max(height(node->left), height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->key)
return rightRotate(node);
if (balance < -1 && key > node->right->key)
return leftRotate(node);
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
void preOrder(Node *root) {
if (root != NULL) {
cout << root->key << " ";
preOrder(root->left);
preOrder(root->right);
}
}
bool isBalanced(Node *root) {
int balance = getBalance(root);
if (balance > 1 || balance < -1)
return false;
else
return true;
}
int main() {
Node *root = NULL;
while (true) {
int val;
cin >> val;
if (val == -1)
break;
root = insert(root, val);
}
if (isBalanced(root))
cout << "The tree is balanced.\n";
else
cout << "The tree is not balanced.\n";
cout << "Preorder traversal of the constructed AVL tree is \n";
preOrder(root);
return 0;
}
@@ -0,0 +1,68 @@
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <cmath>
using namespace std;
const int Base = 31;
const int TableSize = 1000;
struct Node {
string key;
int value;
Node(string key, int value) : key(key), value(value) {}
};
class HashTable {
private:
vector<list<Node>> table;
int hashFunc(string key) {
int hashVal = 0;
for (int i = 0; i < key.length(); i++) {
hashVal = (hashVal + key[i] * static_cast<long long>(pow(Base, i))) % TableSize;
}
return hashVal;
}
public:
HashTable() {
table.resize(TableSize);
}
void insert(string key, int value) {
int hashVal = hashFunc(key);
for (auto &node : table[hashVal]) {
if (node.key == key) {
node.value = value;
return;
}
}
table[hashVal].push_back(Node(key, value));
}
int search(string key) {
int hashVal = hashFunc(key);
for (auto &node : table[hashVal]) {
if (node.key == key) {
return node.value;
}
}
return -1;
}
void destroy() {
for (auto &bucket : table) {
bucket.clear();
}
}
};
int main() {
HashTable ht;
ht.insert("Alice", 1);
ht.insert("Bob", 2);
cout << "Alice: " << ht.search("Alice") << endl;
cout << "Bob: " << ht.search("Bob") << endl;
cout << "Charlie: " << ht.search("Charlie") << endl;
ht.destroy();
return 0;
}
@@ -0,0 +1,152 @@
#include <vector>
#include <iostream>
using namespace std;
// 选择排序
void selectionSort(vector<int> &nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[minIndex]) {
minIndex = j;
}
}
swap(nums[i], nums[minIndex]);
}
}
// 插入排序
void insertionSort(vector<int> &nums) {
int n = nums.size();
for (int i = 1; i < n; i++) {
int key = nums[i];
int j = i - 1;
while (j >= 0 && nums[j] > key) {
nums[j + 1] = nums[j];
j--;
}
nums[j + 1] = key;
}
}
// 归并排序
void merge(vector<int> &nums, int left, int mid, int right) {
vector<int> temp(right - left + 1);
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
temp[k++] = nums[i] <= nums[j] ? nums[i++] : nums[j++];
}
while (i <= mid) {
temp[k++] = nums[i++];
}
while (j <= right) {
temp[k++] = nums[j++];
}
for (int i = left; i <= right; i++) {
nums[i] = temp[i - left];
}
}
void mergeSort(vector<int> &nums, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
merge(nums, left, mid, right);
}
}
// 单指针快速排序
int partitionSingle(vector<int> &nums, int left, int right) {
int pivot = nums[right];
int i = left;
for (int j = left; j < right; j++) {
if (nums[j] < pivot) {
swap(nums[i], nums[j]);
i++;
}
}
swap(nums[i], nums[right]);
return i;
}
void quickSortSingle(vector<int> &nums, int left, int right) {
if (left < right) {
int pivotIndex = partitionSingle(nums, left, right);
quickSortSingle(nums, left, pivotIndex - 1);
quickSortSingle(nums, pivotIndex + 1, right);
}
}
// 双指针快速排序
int partitionDouble(vector<int> &nums, int left, int right) {
int pivot = nums[left];
while (left < right) {
while (left < right && nums[right] >= pivot) {
right--;
}
nums[left] = nums[right];
while (left < right && nums[left] <= pivot) {
left++;
}
nums[right] = nums[left];
}
nums[left] = pivot;
return left;
}
void quickSortDouble(vector<int> &nums, int left, int right) {
if (left < right) {
int pivotIndex = partitionDouble(nums, left, right);
quickSortDouble(nums, left, pivotIndex - 1);
quickSortDouble(nums, pivotIndex + 1, right);
}
}
// 主函数,用于测试上述排序算法
int main() {
vector<int> arr;
int n;
cout << "请输入你想要排序的数字的数量:";
cin >> n;
cout << "请输入这些数字(用空格隔开):";
for (int i = 0; i < n; i++) {
int num;
cin >> num;
arr.push_back(num);
}
selectionSort(arr);
cout << "选择排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
insertionSort(arr);
cout << "插入排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
mergeSort(arr, 0, arr.size() - 1);
cout << "归并排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
quickSortSingle(arr, 0, arr.size() - 1);
cout << "单指针快速排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
quickSortDouble(arr, 0, arr.size() - 1);
cout << "双指针快速排序后的数组:";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << "\n";
return 0;
}
@@ -0,0 +1,83 @@
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// 输入数组元素的函数
vector<int> inputArray(int n) {
vector<int> arr;
int temp;
cout << "请输入数组的元素:";
for (int i = 0; i < n; i++) {
cin >> temp;
arr.push_back(temp);
}
return arr;
}
// 方案一:使用优先队列
void heapSortUsingPriorityQueue(vector<int> &arr) {
priority_queue<int, vector<int>, greater<int>> pq(arr.begin(), arr.end());
int i = 0;
while (!pq.empty()) {
arr[i++] = pq.top();
pq.pop();
}
}
// 方案二:使用向下过滤函数
void heapify(vector<int> &arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(vector<int> &arr) {
int n = arr.size();
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
void printArray(vector<int> &arr) {
for (int i = 0; i < arr.size(); ++i)
cout << arr[i] << " ";
cout << "\n";
}
int main() {
int n;
cout << "请输入数组的元素个数:";
cin >> n;
vector<int> arr = inputArray(n);
heapSortUsingPriorityQueue(arr);
cout << "Sorted array using priority queue is \n";
printArray(arr);
arr = inputArray(n);
heapSort(arr);
cout << "Sorted array using heapify is \n";
printArray(arr);
}
+19
View File
@@ -0,0 +1,19 @@
// 输入若干数据,找出最大值输出。(从键盘和文件读取两种方式)
#include <bits/stdc++.h>
using namespace std;
int main() {
double max;
cin >> max;
double i;
while (cin >> i)
if (i > max)
max = i;
cout << max << endl;
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
#include <bits/stdc++.h>
using namespace std;
int main() {
ifstream in("input.txt");
if (!in) {
cout << "Error opening file";
exit(1);
}
ofstream out("output.txt");
double max;
in >> max;
double i;
while (in >> i)
if (i > max)
max = i;
out << max << endl;
in.close();
out.close();
return 0;
}
+26
View File
@@ -0,0 +1,26 @@
// day(0~6)代表每月第一天起始位置,stop代表每月天数,每天之间空两个空格。输入不同的day和stop,输出每月日历的样子。
#include <bits/stdc++.h>
using namespace std;
int main() {
int day, stop;
cin >> day >> stop;
cout << " Sun Mon Tue Wed Thu Fri Sat" << endl;
int t = day;
while (t--) {
cout << " ";
}
for (int i = 1; i <= stop; i++) {
cout << setw(5) << i;
if ((i + day) % 7 == 0) {
cout << endl;
}
}
return 0;
}
+108
View File
@@ -0,0 +1,108 @@
// 实现 Set 模板类,并重载 +、<< 和 >> 操作符
#include <bits/stdc++.h>
using namespace std;
template <typename T = int>
class Set {
private:
vector<T> a;
public:
int search(const T &) const;
int operator()(const T &);
int del(const T &);
Set<T> operator*(const Set<T> &) const;
Set<T> operator+(const Set<T> &) const;
Set<T> operator-(const Set<T> &) const;
template <typename S>
friend ostream &operator<<(ostream &output, const Set<S> &s);
template <typename S>
friend istream &operator>>(istream &input, Set<S> &s);
};
template <typename T>
int Set<T>::search(const T &x) const {
for (int i = 0; i < a.size(); i++)
if (a[i] == x)
return i;
return -1;
}
template <typename T>
int Set<T>::operator()(const T &x) {
if (search(x) != -1)
return 0;
a.push_back(x);
return 1;
}
template <typename T>
int Set<T>::del(const T &x) {
int i = search(x);
if (i == -1)
return 0;
a.erase(a.begin() + i);
return 1;
}
template <typename T>
Set<T> Set<T>::operator*(const Set<T> &s) const {
Set<T> t;
for (int i = 0; i < a.size(); i++)
if (s.search(a[i]) != -1)
t(a[i]);
return t;
}
template <typename T>
Set<T> Set<T>::operator+(const Set<T> &s) const {
Set t = *this;
for (int i = 0; i < s.a.size(); i++)
t(s.a[i]);
return t;
}
template <typename T>
Set<T> Set<T>::operator-(const Set<T> &s) const {
Set t;
for (int i = 0; i < a.size(); i++)
if (s.search(a[i]) == -1)
t(a[i]);
return t;
}
template <typename T>
ostream &operator<<(ostream &output, const Set<T> &s) {
for (int i = 0; i < s.a.size(); i++)
output << s.a[i] << ' ';
return output;
}
template <typename T>
istream &operator>>(istream &input, Set<T> &s) {
s.a.clear();
int x;
while (input >> x)
s(x);
return input;
}
int main() {
Set<int> s1, s2;
cout << "s1: ";
cin >> s1;
s2(9);
s2(10);
s2(11);
s2(12);
s2(13);
s2(14);
s2(15);
cout << "s2: " << s2 << endl;
cout << "s1 * s2: " << s1 * s2 << endl;
cout << "s1 + s2: " << s1 + s2 << endl;
cout << "s1 - s2: " << s1 - s2 << endl;
return 0;
}
+41
View File
@@ -0,0 +1,41 @@
// 设计实现一个函数模板,实现任意数据类型的查找
#include <bits/stdc++.h>
using namespace std;
template <typename T>
int find(const T *a, const int &n, const T &x) {
for (int i = 0; i < n; i++)
if (a[i] == x)
return i;
return -1;
}
int find(const string &s, const char &x) {
for (int i = 0; i < s.length(); i++)
if (s[i] == x)
return i;
return -1;
}
template <typename T>
int find(const vector<T> &v, const T &x) {
for (int i = 0; i < v.size(); i++)
if (v[i] == x)
return i;
return -1;
}
int main() {
int i[5] = { 1, 2, 3, 4, 5 };
double f[5] = { 1.4, 2.4, 3.4, 4.4, 5.4 };
string s = "Hello, world!\n";
vector<int> vi = { 6, 7, 8, 9, 0 };
vector<double> vd = { 435.6, 57.65, 57.5, 64.5 };
cout << find(i, 5, 1) << ' ' << find(i, 5, 6) << endl
<< find(f, 5, 2.4) << ' ' << find(f, 5, 7.5) << endl
<< find(s, '\n') << ' ' << find(s, 'a') << endl
<< find(vi, 9) << ' ' << find(vi, 1) << endl
<< find(vd, 57.5) << ' ' << find(vd, 5.2) << endl;
}
+133
View File
@@ -0,0 +1,133 @@
// 实现电话簿管理程序, Mytel类描述单个电话号码,TelManager类负责管理电话号码。把增、删、改、查功能封装到该类中。要求电话号码能从磁盘读写。
#include <bits/stdc++.h>
using namespace std;
class Mytel {
public:
void getdata() { cin >> name >> telno; }
void setname(char a[]) { strcpy(name, a); }
void settelno(char a[]) { strcpy(telno, a); }
void putdata() { cout << name << setw(12) << telno << endl; }
string getname() { return name; }
string gettelno() { return telno; }
private:
char name[12];
char telno[12];
};
class TelManager {
private:
vector<Mytel> a;
public:
void loadfile() {
ifstream input("phone.txt");
if (!input) {
cout << "File cannot be opened." << endl;
return;
}
Mytel s;
char name[12], telno[12];
input >> name >> telno;
s.setname(name);
s.settelno(telno);
while (input) {
a.push_back(s);
input >> name >> telno;
s.setname(name);
s.settelno(telno);
};
input.close();
}
void display() {
cout << "姓名" << setw(8) << "电话" << endl;
for (int i = 0; i < a.size(); i++)
cout << a[i].getname() << setw(12) << a[i].gettelno() << endl;
}
void search() {
string sname;
cout << "输入要查询的姓名(可只输入姓氏):";
cin >> sname;
cout << "输出查询结果:" << endl;
cout << "姓名" << setw(8) << "电话" << endl;
for (int i = 0; i < a.size(); i++)
if (a[i].getname() == sname)
a[i].putdata();
}
void add() {
Mytel one;
cout << "姓名" << setw(8) << "电话" << endl;
one.getdata();
a.push_back(one);
}
void del() {
string dname;
cout << "输入要删除的姓名(可只输入姓氏):";
cin >> dname;
for (int i = 0; i < a.size(); i++)
if (a[i].getname() == dname)
a.erase(a.begin() + i);
}
void modify() {
string mname;
char mtelno[12];
cout << "输入要修改的姓名(可只输入姓氏):";
cin >> mname;
for (int i = 0; i < a.size(); i++)
if (a[i].getname() == mname) {
cout << "电话:";
cin >> mtelno;
a[i].settelno(mtelno);
}
}
void writefile() {
ofstream file("phone.txt");
for (int i = 0; i < a.size(); i++)
file << a[i].getname() << "\t" << a[i].gettelno() << endl;
file.close();
}
};
int main() {
int sel;
TelManager m;
while (1) {
cout << "***********************电话薄管理系统***********************";
cout << endl
<< endl;
cout << "1:加载数据 2:输出数据 3:按姓名查询 4:添加数据" << endl
<< "5:删除数据 6:修改数据 7.保存数据 0:退出" << endl;
cout << "************************************************************";
cout << "\n请选择 (0 - 7): ";
cin >> sel;
switch (sel) {
case 1:
m.loadfile();
break;
case 2:
m.display();
break;
case 3:
m.search();
break;
case 4:
m.add();
break;
case 5:
m.del();
break;
case 6:
m.modify();
break;
case 7:
m.writefile();
break;
case 0:
exit(1);
}
}
return 0;
}
+53
View File
@@ -0,0 +1,53 @@
// 写一个程序,将 24 小时格式时间转换为 12 小时格式。定义一个名为 TimeMistake 的异常类,处理用户输入的非法时间,比如 10:65 或者无效字符。
#include <bits/stdc++.h>
using namespace std;
class TimeMistake {
string message;
public:
TimeMistake(string msg) { message = msg; }
string getMessage() { return message; }
};
void test() {
cout << "Please enter a time in 24-hour format (such as 14:30): ";
string input;
cin >> input;
if (input.length() != 5 || input[2] != ':')
throw TimeMistake("Invalid time format");
else {
int hour = stoi(input.substr(0, 2));
int min = stoi(input.substr(3, 2));
if (hour < 0 || hour > 23 || min < 0 || min > 59)
throw TimeMistake("Invalid time value");
bool am = true;
if (hour > 12) {
am = false;
hour -= 12;
}
if (hour == 0)
hour = 12;
cout << "The converted 12 hour format time is: " << setfill('0') << setw(2) << hour << ':' << setw(2) << min << ' ';
if (am)
cout << "AM";
else
cout << "PM";
}
}
void handler() {
try {
test();
}
catch (TimeMistake e) {
cerr << "An error occurred: " << e.getMessage() << endl;
}
}
int main() {
handler();
return 0;
}
+22
View File
@@ -0,0 +1,22 @@
// 设计一个函数print打印字符串,如果只传string型参数s,则字符串长度跟10比较,大于10,打印前10个字符,小于10,全部输出s;如果传string型参数s和int型n,则字符串长度跟n比较,大于n,打印前n个字符,小于n,全部输出s。
#include <bits/stdc++.h>
using namespace std;
void print(string s, int n = 10) {
cout << s.substr(0, n) << endl;
}
int main() {
string s;
int n;
cin >> s;
print(s);
cin >> s >> n;
print(s, n);
return 0;
}
+29
View File
@@ -0,0 +1,29 @@
// 输入10个人的名字,按从大到小排序输出。
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<string> names;
string input;
cout << "请输入若干姓名,以空格分隔,按回车结束:" << endl;
getline(cin, input);
stringstream ss(input);
string name;
while (ss >> name)
names.push_back(name);
sort(names.begin(), names.end());
cout << "排序后的姓名为:" << endl;
for (int i = 0; i < names.size(); i++)
cout << names[i] << " ";
cout << endl;
return 0;
}
+44
View File
@@ -0,0 +1,44 @@
// 模仿二维数组,使用引用调用和引用返回,把函数代码补完整。
#include <bits/stdc++.h>
using namespace std;
struct twodim {
int r;
int c;
float *a;
};
void get_twodim(twodim &s, int row, int col) {
// 初始化数组
s.r = row;
s.c = col;
s.a = new float[s.r * s.c];
}
float &val(twodim &s, int i, int j) {
// 返回i行j列的值
return s.a[i * s.c + j];
}
void free_twodim(twodim &s) {
// 释放数组空间
delete[] s.a;
}
int main() {
struct twodim s;
int i, j;
get_twodim(s, 3, 4);
for (i = 0; i < 3; i++)
for (j = 0; j < 4; j++)
val(s, i, j) = i + j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++)
cout << setw(5) << val(s, i, j);
cout << endl;
}
free_twodim(s);
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
// 设计一个Circle类,有数据成员radius(半径)、成员函数area(),计算圆的面积。构造一个Circle对象进行测试。
#include <bits/stdc++.h>
using namespace std;
class Circle {
private:
double radius;
public:
void setRadius(double r) { radius = r; }
double area() { return M_PI * radius * radius; }
};
int main() {
Circle c;
double r;
cin >> r;
c.setRadius(r);
cout << "Area of circle: " << c.area() << endl;
return 0;
}
+63
View File
@@ -0,0 +1,63 @@
// 字符串序列类的设计:类Sequence的定义
#include <bits/stdc++.h>
using namespace std;
class Sequence {
private:
int last;
string s[100];
public:
void init();
void append(string);
void del(string);
void output();
};
void Sequence::init() {
last = -1;
}
void Sequence::append(string x) {
s[++last] = x;
}
void Sequence::del(string x) {
for (int i = 0; i <= last; i++)
if (s[i] == x) {
for (int j = i; j < last; j++)
s[j] = s[j + 1];
last--;
break;
}
}
void Sequence::output() {
for (int i = 0; i <= last; i++)
cout << s[i] << ' ';
cout << '\n';
}
int main() {
Sequence seq;
seq.init();
seq.append("a");
seq.append("b");
seq.append("c");
seq.append("d");
seq.append("e");
seq.append("f");
seq.append("g");
seq.append("h");
seq.output();
seq.del("b");
seq.del("d");
seq.del("f");
seq.del("h");
seq.output();
return 0;
}
+115
View File
@@ -0,0 +1,115 @@
// 设计和实现整型集合类(Set),成员函数要求如下:
// 添加构造函数完成初始化
// 能添加一个元素,元素不重复
// 能删除一个元素
// 输出所有元素
// 求两个集合对象的交集
// 求两个集合对象的并集
// 求两个集合对象的差集
// 1_1.cpp
#include <bits/stdc++.h>
using namespace std;
class Set {
private:
vector<int> a;
public:
int search(int);
int add(int);
int del(int);
void output();
Set operator&(Set &);
Set operator|(Set &);
Set operator-(Set &);
};
int Set::search(int x) {
for (int i = 0; i < a.size(); i++)
if (a[i] == x)
return i;
return -1;
}
int Set::add(int x) {
if (search(x) != -1)
return 0;
a.push_back(x);
return 1;
}
int Set::del(int x) {
int i = search(x);
if (i == -1)
return 0;
a.erase(a.begin() + i);
return 1;
}
void Set::output() {
for (int i = 0; i < a.size(); i++) {
cout << a[i] << ' ';
}
cout << '\n';
}
Set Set::operator&(Set &s) {
Set t;
for (int i = 0; i < a.size(); i++)
if (s.search(a[i]) != -1)
t.add(a[i]);
return t;
}
Set Set::operator|(Set &s) {
Set t = *this;
for (int i = 0; i < s.a.size(); i++)
t.add(s.a[i]);
return t;
}
Set Set::operator-(Set &s) {
Set t;
for (int i = 0; i < a.size(); i++)
if (s.search(a[i]) == -1)
t.add(a[i]);
return t;
}
int main() {
Set s1, s2;
s1.add(1);
s1.add(2);
s1.add(3);
s1.add(4);
s1.add(5);
s1.add(6);
s1.add(7);
s1.add(8);
s1.add(9);
s1.add(10);
cout << "s1: ";
s1.output();
s2.add(9);
s2.add(10);
s2.add(11);
s2.add(12);
s2.add(13);
s2.add(14);
s2.add(15);
cout << "s2: ";
s2.output();
Set s3 = s1 & s2;
cout << "s1 & s2: ";
s3.output();
Set s4 = s1 | s2;
cout << "s1 | s2: ";
s4.output();
Set s5 = s1 - s2;
cout << "s1 - s2: ";
s5.output();
return 0;
}
+118
View File
@@ -0,0 +1,118 @@
// 1_2.cpp
#include <bits/stdc++.h>
using namespace std;
class Set {
private:
int *a;
int cnt;
int size;
public:
Set(int = 100);
int search(int);
int add(int);
int del(int);
void output();
Set intersection(Set &);
Set sum(Set &);
Set difference(Set &);
};
Set::Set(int n) {
a = new int[n];
cnt = 0;
size = n;
}
int Set::search(int x) {
for (int i = 0; i < cnt; i++)
if (a[i] == x)
return i;
return -1;
}
int Set::add(int x) {
if (search(x) != -1)
return 0;
if (cnt == size)
return 0;
a[cnt++] = x;
return 1;
}
int Set::del(int x) {
int i = search(x);
if (i == -1)
return 0;
for (int j = i; j < cnt - 1; j++)
a[j] = a[j + 1];
cnt--;
return 1;
}
void Set::output() {
for (int i = 0; i < cnt; i++)
cout << a[i] << " ";
cout << '\n';
}
Set Set::intersection(Set &s) {
Set t;
for (int i = 0; i < cnt; i++)
if (s.search(a[i]) != -1)
t.add(a[i]);
return t;
}
Set Set::sum(Set &s) {
Set t = *this;
for (int i = 0; i < s.cnt; i++)
t.add(s.a[i]);
return t;
}
Set Set::difference(Set &s) {
Set t;
for (int i = 0; i < cnt; i++)
if (s.search(a[i]) == -1)
t.add(a[i]);
return t;
}
int main() {
Set s1, s2;
s1.add(1);
s1.add(2);
s1.add(3);
s1.add(4);
s1.add(5);
s1.add(6);
s1.add(7);
s1.add(8);
s1.add(9);
s1.add(10);
cout << "s1: ";
s1.output();
s2.add(9);
s2.add(10);
s2.add(11);
s2.add(12);
s2.add(13);
s2.add(14);
s2.add(15);
cout << "s2: ";
s2.output();
Set s3 = s1.intersection(s2);
cout << "s1 & s2: ";
s3.output();
Set s4 = s1.sum(s2);
cout << "s1 | s2: ";
s4.output();
Set s5 = s1.difference(s2);
cout << "s1 - s2: ";
s5.output();
return 0;
}
+59
View File
@@ -0,0 +1,59 @@
// 编程实现Student类,在该类中设计静态数据成员segment1、segment2、segment3、segment4、segment5分别统计分数100-90、89-80,、79-70、69-60、59-0学生人数。设计静态成员函数display()显示各分数段人数。
#include <bits/stdc++.h>
using namespace std;
class Student {
private:
static int segment1;
static int segment2;
static int segment3;
static int segment4;
static int segment5;
public:
Student(int score);
static void display();
};
int Student::segment1 = 0;
int Student::segment2 = 0;
int Student::segment3 = 0;
int Student::segment4 = 0;
int Student::segment5 = 0;
Student::Student(int score) {
if (score >= 90 && score <= 100)
segment1++;
else if (score >= 80 && score < 90)
segment2++;
else if (score >= 70 && score < 80)
segment3++;
else if (score >= 60 && score < 70)
segment4++;
else if (score >= 0 && score < 60)
segment5++;
else
cout << "Invalid score: " << score << endl;
}
void Student::display() {
cout << "Segment1: " << segment1 << endl;
cout << "Segment2: " << segment2 << endl;
cout << "Segment3: " << segment3 << endl;
cout << "Segment4: " << segment4 << endl;
cout << "Segment5: " << segment5 << endl;
}
int main() {
Student s0(115);
Student s1(95);
Student s2(85);
Student s3(75);
Student s4(65);
Student s5(55);
Student s6(45);
Student::display();
return 0;
}
+68
View File
@@ -0,0 +1,68 @@
// 设计一个类层次,基类为Date,从Date分别派生出ShortE、MediumDate和LongDate.他们各自有成员函数print(),输出当前日期。
// Date输出日期格式为:04-14-2018
// ShortE输出日期格式为:14-04-2018
// MediumDate输出日期格式为:Apr.14,2018
// LongDate输出日期格式为:April 14, 2018
// class Date
// {
// protected:
// int year, month, day;
// };
#include <bits/stdc++.h>
using namespace std;
class Date {
protected:
int year, month, day;
public:
Date() {
time_t t = time(nullptr);
tm *lt = localtime(&t);
year = lt->tm_year + 1900;
month = lt->tm_mon + 1;
day = lt->tm_mday;
}
void print() { cout << setfill('0') << setw(2) << month << '-' << setw(2) << day << '-' << setw(4) << year << endl; }
};
class ShortE : public Date {
public:
ShortE() : Date() {}
void print() { cout << setfill('0') << setw(2) << day << '-' << setw(2) << month << '-' << setw(4) << year << endl; }
};
class MediumDate : public Date {
public:
MediumDate() : Date() {}
void print() {
string months[12] = { "Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec." };
cout << months[month - 1] << day << ',' << year << endl;
}
};
class LongDate : public Date {
public:
LongDate() : Date() {}
void print() {
string months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
cout << months[month - 1] << ' ' << day << ", " << year << endl;
}
};
int main() {
Date d;
ShortE s;
MediumDate m;
LongDate l;
d.print();
s.print();
m.print();
l.print();
return 0;
}
+48
View File
@@ -0,0 +1,48 @@
// Figure 类有一个数据成员radius和虚函数area ()和volume()。从Figure类派生出Sphere类和Column类,分别实现求球体和圆柱体的体积和表面积。并编写测试程序。
#include <bits/stdc++.h>
const double PI = 3.14;
using namespace std;
class Figure {
protected:
double radius;
public:
virtual double area() const { return 0.0; }
virtual double volume() const { return 0.0; }
};
class Sphere : public Figure {
public:
Sphere(double myr) { radius = myr; }
virtual double area() const { return 4 * PI * radius * radius; }
virtual double volume() const { return 4 * PI * radius * radius * radius / 3; }
};
class Column : public Figure {
public:
Column(double myr, double myh) {
radius = myr;
height = myh;
}
virtual double area() const { return 2 * PI * radius * height; }
virtual double volume() const { return PI * radius * radius * height; }
private:
double height;
};
void func(Figure &p) {
cout << p.area() << endl;
}
int main() {
Sphere s(1);
Column c(1, 2);
func(s);
func(c);
return 0;
}
+87
View File
@@ -0,0 +1,87 @@
// 某学校对教师每月工资的计算规定如下:固定工资+课时补贴;教授每课时50元;副教授每课时30元;讲师每课时20元。定义教师抽象类,派生出不同职称的教师类,编写程序求若干个教师的月工资。
// 职称 等级 每月固定工资(元)
// 教授 一级 8000
// 二级 7500
// 副教授 一级 7000
// 二级 6000
// 三级 5000
// 讲师 4500
#include <bits/stdc++.h>
using namespace std;
class Teacher {
protected:
double fixed_salary;
double class_hour_subsidy;
public:
double calculate_salary(int class_hours) {
return fixed_salary + class_hour_subsidy * class_hours;
}
};
class Professor : public Teacher {
private:
int level;
public:
Professor(int l) : level(l) {
switch (level) {
case 1:
fixed_salary = 8000;
break;
case 2:
fixed_salary = 7500;
break;
default:
fixed_salary = 0;
break;
}
class_hour_subsidy = 50;
}
};
class AssociateProfessor : public Teacher {
private:
int level;
public:
AssociateProfessor(int l) : level(l) {
switch (level) {
case 1:
fixed_salary = 7000;
break;
case 2:
fixed_salary = 6000;
break;
case 3:
fixed_salary = 5000;
break;
default:
fixed_salary = 0;
break;
}
class_hour_subsidy = 30;
}
};
class Lecturer : public Teacher {
public:
Lecturer() {
fixed_salary = 4500;
class_hour_subsidy = 20;
}
};
int main() {
Professor p(1), p2(2);
AssociateProfessor ap(1), ap2(2), ap3(3);
Lecturer l;
Teacher *t[7] = { &p, &p2, &ap, &ap2, &ap3, &l };
for (int i = 0; i < 6; i++) {
cout << t[i]->calculate_salary(10) << endl;
}
return 0;
}
+117
View File
@@ -0,0 +1,117 @@
#include <bits/stdc++.h>
using namespace std;
class Teacher {
protected:
int no;
string name;
float salary;
static int totalno;
public:
Teacher() {
no = totalno++;
cout << "教师姓名:";
cin >> name;
salary = 0.0;
}
virtual void pay() = 0;
virtual void display() = 0;
};
int Teacher::totalno = 10000;
class Professor : public Teacher {
private:
int level;
float fixed;
float hourlyrate;
int classhours;
public:
Professor(int l) {
level = l;
fixed = 0.0;
hourlyrate = 50.0;
cout << name << "本月课时:";
cin >> classhours;
}
void pay() {
if (level == 1)
fixed = 8000.0;
else if (level == 2)
fixed = 7500.0;
salary = fixed + hourlyrate * classhours;
}
void display() {
cout << "教授:" << name << ",编号:" << no << ",本月工资:" << salary << endl;
}
};
class AssociateProfessor : public Teacher {
private:
int level;
float fixed;
float hourlyrate;
int classhours;
public:
AssociateProfessor(int l) {
level = l;
fixed = 0.0;
hourlyrate = 30.0;
cout << name << "本月课时:";
cin >> classhours;
}
void pay() {
if (level == 1)
fixed = 7000.0;
else if (level == 2)
fixed = 6000.0;
else if (level == 3)
fixed = 5000.0;
salary = fixed + hourlyrate * classhours;
}
void display() {
cout << "副教授:" << name << ",编号:" << no << ",本月工资:" << salary << endl;
}
};
class Lecturer : public Teacher {
private:
float fixed;
float hourlyrate;
int classhours;
public:
Lecturer() {
fixed = 4500.0;
hourlyrate = 20.0;
cout << "本月课时:";
cin >> classhours;
}
void pay() {
salary = fixed + hourlyrate * classhours;
}
void display() {
cout << "讲师:" << name << ",编号:" << no << ",本月工资:" << salary << endl;
}
};
int main() {
Professor p1(1);
Professor p2(2);
AssociateProfessor a1(1);
AssociateProfessor a2(2);
AssociateProfessor a3(3);
Lecturer l;
Teacher *t[6] = { &p1, &p2, &a1, &a2, &a3, &l };
cout << "------------------------------------------" << endl;
cout << "上述教师的基本信息为:" << endl;
for (int i = 0; i < 6; i++) {
t[i]->pay();
t[i]->display();
}
return 0;
}
+111
View File
@@ -0,0 +1,111 @@
// 定义一个有理数类。一个有理数类是一个可以表示成两个整数相除的数,如1/2、2/3、4/5。一个有理数类有两个整数成员表示:分子和分母。要求能检测分母为0问题,能化简,重载+、-、*、/运算符完成四则运算,重载“==”符号判断两个有理数是否相等
#include <bits/stdc++.h>
using namespace std;
class Rational {
private:
int numerator;
int denominator;
public:
Rational(int num, int den);
Rational operator+(const Rational &r) const;
Rational operator-(const Rational &r) const;
Rational operator*(const Rational &r) const;
Rational operator/(const Rational &r) const;
bool operator==(const Rational &r) const;
friend ostream &operator<<(ostream &output, const Rational &r);
};
Rational::Rational(int num, int den) {
numerator = num;
denominator = den;
if (numerator == 0 && denominator == 0)
;
else if (numerator == 0)
denominator = 1;
else if (denominator == 0)
numerator = 1;
else {
int _gcd = gcd(numerator, denominator);
numerator /= _gcd;
denominator /= _gcd;
if (denominator < 0) {
numerator *= -1;
denominator *= -1;
}
}
}
Rational Rational::operator+(const Rational &r) const {
int num, den;
if (numerator != 0 && r.numerator != 0 && denominator == 0 && r.denominator == 0) {
num = 1;
den = 0;
}
else {
num = numerator * r.denominator + r.numerator * denominator;
den = denominator * r.denominator;
}
return Rational(num, den);
}
Rational Rational::operator-(const Rational &r) const {
int num = numerator * r.denominator - r.numerator * denominator;
int den = denominator * r.denominator;
return Rational(num, den);
}
Rational Rational::operator*(const Rational &r) const {
int num = numerator * r.numerator;
int den = denominator * r.denominator;
return Rational(num, den);
}
Rational Rational::operator/(const Rational &r) const {
int num, den;
if (denominator == 0 && r.denominator == 0) {
num = 0;
den = 0;
}
else {
num = numerator * r.denominator;
den = r.numerator * denominator;
}
return Rational(num, den);
}
bool Rational::operator==(const Rational &r) const {
return numerator == r.numerator && denominator == r.denominator;
}
ostream &operator<<(ostream &output, const Rational &r) {
if (r.numerator == 0 && r.denominator == 0)
output << "NaN";
else if (r.denominator == 0)
output << "Inf";
else
output << r.numerator << " / " << r.denominator;
return output;
}
int main() {
char c;
int num1, den1, num2, den2;
cout << "r1 = ";
cin >> num1 >> c >> den1;
cout << "r2 = ";
cin >> num2 >> c >> den2;
Rational r1(num1, den1), r2(num2, den2);
cout << "r1 + r2 = " << r1 + r2 << endl
<< "r1 - r2 = " << r1 - r2 << endl
<< "r1 * r2 = " << r1 * r2 << endl
<< "r1 / r2 = " << r1 / r2 << endl;
if (r1 == r2)
cout << "r1 == r2" << endl;
else
cout << "r1 != r2" << endl;
return 0;
}
+99
View File
@@ -0,0 +1,99 @@
// 改造Set类,重载+(并集)、(-)差集、*(交集)、<<(输出)、>>(输入)和函数调用操作符(添加一个元素)
#include <bits/stdc++.h>
using namespace std;
class Set {
private:
vector<int> a;
public:
int search(int);
int operator()(int x);
int del(int);
Set operator*(Set &);
Set operator+(Set &);
Set operator-(Set &);
friend ostream &operator<<(ostream &output, const Set &s);
friend istream &operator>>(istream &input, Set &s);
};
int Set::search(int x) {
for (int i = 0; i < a.size(); i++)
if (a[i] == x)
return i;
return -1;
}
int Set::operator()(int x) {
if (search(x) != -1)
return 0;
a.push_back(x);
return 1;
}
int Set::del(int x) {
int i = search(x);
if (i == -1)
return 0;
a.erase(a.begin() + i);
return 1;
}
Set Set::operator*(Set &s) {
Set t;
for (int i = 0; i < a.size(); i++)
if (s.search(a[i]) != -1)
t(a[i]);
return t;
}
Set Set::operator+(Set &s) {
Set t = *this;
for (int i = 0; i < s.a.size(); i++)
t(s.a[i]);
return t;
}
Set Set::operator-(Set &s) {
Set t;
for (int i = 0; i < a.size(); i++)
if (s.search(a[i]) == -1)
t(a[i]);
return t;
}
ostream &operator<<(ostream &output, const Set &s) {
for (int i = 0; i < s.a.size(); i++) {
output << s.a[i] << ' ';
}
return output;
}
istream &operator>>(istream &input, Set &s) {
s.a.clear();
int x;
while (input >> x) {
s(x);
}
return input;
}
int main() {
Set s1, s2;
cout << "s1: ";
cin >> s1;
s2(9);
s2(10);
s2(11);
s2(12);
s2(13);
s2(14);
s2(15);
cout << "s2: " << s2 << endl;
cout << "s1 * s2: " << s1 * s2 << endl;
cout << "s1 + s2: " << s1 + s2 << endl;
cout << "s1 - s2: " << s1 - s2 << endl;
return 0;
}
@@ -0,0 +1,68 @@
// Copyright (c) 2023 徐丞烨,王凯钦,宋析峰,杨崇新
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
// 定义一个函数,用于计算表达式的值
double Evalue(stringstream &exp) {
string e;
exp >> e;
// 如果是加法
if (e == "add")
// 递归计算左右两个操作数的值并相加
return Evalue(exp) + Evalue(exp);
// 如果是减法
else if (e == "sub")
// 递归计算左右两个操作数的值并相减
return Evalue(exp) - Evalue(exp);
// 如果是乘法
else if (e == "muti")
// 递归计算左右两个操作数的值并相乘
return Evalue(exp) * Evalue(exp);
// 如果是除法
else if (e == "div")
// 递归计算左右两个操作数的值并相除
return Evalue(exp) / Evalue(exp);
// 如果是取负
else if (e == "neg") {
double temp;
exp >> temp;
// 取负并返回
return -temp;
}
// 如果是平方
else if (e == "doubleMe") {
double temp;
exp >> temp;
// 平方并返回
return temp * temp;
}
// 如果是数字
else
// 直接返回数字
return atof(e.c_str());
}
int main() {
// 从文件中读取表达式
ifstream fin("E:\\OneDrive\\Code\\C++\\Professional-Comprehensive-Training-I\\question.txt");
// 将计算结果写入文件
ofstream fout("E:\\OneDrive\\Code\\C++\\Professional-Comprehensive-Training-I\\answer.txt");
string line;
while (getline(fin, line)) {
string temp = line;
// 将括号和逗号替换为空格
for (char &c : temp)
if (c == '(' || c == ')' || c == ',')
c = ' ';
// 将表达式转换为流并计算结果
stringstream exp(temp);
fout << line << " = " << Evalue(exp) << endl;
}
// 关闭文件
fin.close();
fout.close();
return 0;
}
@@ -0,0 +1,155 @@
// Copyright (c) 2023 徐丞烨,王凯钦,宋析峰,杨崇新
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
// 定义节点结构体
struct Node {
char operato; // 运算符
double operand; // 操作数
Node *left; // 左子树
Node *right; // 右子树
Node(char o = 0, double d = 0, Node *l = nullptr, Node *r = nullptr) : operato(o), operand(d), left(l), right(r) {}
};
// 定义树类型
using Tree = Node *;
// 递归构建表达式树
Tree buildTree(stringstream &ss) {
string e;
ss >> e;
// 如果是加法
if (e == "add") {
Tree t = new Node('+');
t->left = buildTree(ss);
t->right = buildTree(ss);
return t;
}
// 如果是减法
else if (e == "sub") {
Tree t = new Node('-');
t->left = buildTree(ss);
t->right = buildTree(ss);
return t;
}
// 如果是乘法
else if (e == "muti") {
Tree t = new Node('*');
t->left = buildTree(ss);
t->right = buildTree(ss);
return t;
}
// 如果是除法
else if (e == "div") {
Tree t = new Node('/');
t->left = buildTree(ss);
t->right = buildTree(ss);
return t;
}
// 如果是取负
else if (e == "neg") {
double temp;
ss >> temp;
return new Node(0, -temp);
}
// 如果是平方
else if (e == "doubleMe") {
Tree t = new Node('^');
double temp;
ss >> temp;
t->left = new Node(0, temp);
t->right = new Node(0, 2);
return t;
}
// 如果是数字
else
return new Node(0, atof(e.c_str()));
}
// 判断节点是否为运算符
bool isOperator(const Tree t) {
return t->operato != 0;
}
// 定义运算符优先级
map<char, int> priority{ { '+', 1 }, { '-', 1 }, { '*', 2 }, { '/', 2 }, { '^', 3 } };
// 判断运算符优先级是否小于等于另一个运算符
bool lowerOrEqualPrecedence(const char op1, const char op2) {
return priority[op1] <= priority[op2];
}
// 输出表达式树
void print(ostream &out, const Tree t = nullptr) {
if (t == nullptr)
return;
if (isOperator(t)) {
bool leftParen = isOperator(t->left) && lowerOrEqualPrecedence(t->left->operato, t->operato);
bool rightParen = isOperator(t->right) && lowerOrEqualPrecedence(t->right->operato, t->operato);
if (leftParen)
out << "(";
print(out, t->left);
if (leftParen)
out << ")";
out << ' ' << t->operato << ' ';
if (rightParen)
out << "(";
print(out, t->right);
if (rightParen)
out << ")";
}
else
out << t->operand;
}
// 计算表达式树的值
double evaluate(const Tree t) {
if (t == nullptr)
return 0;
if (isOperator(t)) {
double left = evaluate(t->left);
double right = evaluate(t->right);
switch (t->operato) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '^':
return pow(left, right);
}
}
return t->operand;
}
int main() {
// 从文件中读取表达式
ifstream fin("E:\\OneDrive\\Code\\C++\\Professional-Comprehensive-Training-I\\question.txt");
// 将计算结果写入文件
ofstream fout("E:\\OneDrive\\Code\\C++\\Professional-Comprehensive-Training-I\\answer.txt");
string line;
while (getline(fin, line)) {
string temp = line;
// 将括号和逗号替换为空格
for (char &c : temp)
if (c == '(' || c == ')' || c == ',')
c = ' ';
// 将表达式转换为流并构建表达式树
stringstream ss(temp);
Tree t = buildTree(ss);
// 输出表达式和计算结果
print(fout, t);
fout << " = " << evaluate(t);
fout << endl;
}
// 关闭文件
fin.close();
fout.close();
return 0;
}
@@ -0,0 +1,322 @@
// Copyright (c) 2023 徐丞烨,王凯钦,宋析峰,杨崇新
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
// 定义一个结构体,表示一条记录
struct Record {
int id; // 记录的id
string name; // 记录的名字
bool isMale; // 记录的性别
double data; // 记录的数据
Record(int id = 0, string name = "", bool isMale = true, double data = 0) : id(id), name(name), isMale(isMale), data(data) {}
};
// 定义一个比较函数对象,用于将记录按照id从小到大排序
struct cmp {
bool operator()(const Record &a, const Record &b) const {
return a.id < b.id;
}
};
// 从输入流in中读取记录,将记录插入到set中并返回
set<Record, cmp> table(istream &in) {
set<Record, cmp> table; // 定义一个set,用于存储记录
while (!in.eof()) // 循环读取输入流中的记录
{
int id;
string name, gender;
bool isMale;
double data;
in >> id >> name >> gender >> data; // 从输入流中读取记录的各个字段
if (gender == "male") // 判断记录的性别
isMale = true;
else
isMale = false;
table.insert(Record(id, name, isMale, data)); // 将记录插入到set中
}
return table; // 返回set
}
int main() {
string sql;
while (getline(cin, sql)) // 从标准输入读取一行 SQL 语句
{
ifstream sfin("stu.txt"), efin("employee.txt"); // 打开两个文件
if (!sfin.is_open() || !efin.is_open()) // 如果文件打开失败
{
cout << "File not found!" << endl; // 输出错误信息
return 0; // 退出程序
}
set<Record, cmp> stu = table(sfin), employee = table(efin); // 从文件中读取数据并存储到 set 容器中
sfin.close(), efin.close(); // 关闭文件
if (sql == "EXIT") // 如果输入的 SQL 语句为 EXIT
break; // 退出循环
stringstream ss(sql); // 将 SQL 语句转换为 stringstream 流
string tmp;
bool col[4], isStu, isMale;
double limits;
ss >> tmp;
if (tmp != "SELECT") // 如果 SQL 语句不是 SELECT
{
cout << "Invalid SQL!" << endl; // 输出错误信息
continue; // 继续下一次循环
}
ss >> tmp;
if (tmp == "*") // 如果 SQL 语句为 SELECT *
{
for (bool &b : col)
b = true; // 将 col 数组中的所有元素都设置为 true
ss >> tmp;
}
else {
bool conti = false;
for (bool &b : col)
b = false; // 将 col 数组中的所有元素都设置为 false
do {
if (tmp == "ID" || tmp == "ID,")
col[0] = true; // 如果 SQL 语句中包含 ID,将 col[0] 设置为 true
else if (tmp == "Name" || tmp == "Name,")
col[1] = true; // 如果 SQL 语句中包含 Name,将 col[1] 设置为 true
else if (tmp == "Gender" || tmp == "Gender,")
col[2] = true; // 如果 SQL 语句中包含 Gender,将 col[2] 设置为 true
else if (tmp == "Score" || tmp == "Score," || tmp == "Salary" || tmp == "Salary,")
col[3] = true; // 如果 SQL 语句中包含 Score 或 Salary,将 col[3] 设置为 true
else {
if (tmp != "FROM") {
cout << "The type of data does not exist!" << endl; // 输出错误信息
conti = true; // 设置 conti 为 true
}
break;
}
} while (ss >> tmp);
if (conti)
continue; // 继续下一次循环
}
if (tmp != "FROM") // 如果 SQL 语句不是 FROM
{
cout << "Invalid SQL!" << endl; // 输出错误信息
continue; // 继续下一次循环
}
else {
ss >> tmp;
if (tmp != "stu" && tmp != "employee") // 如果 SQL 语句中不包含 stu 或 employee
{
cout << "The table does not exist!" << endl; // 输出错误信息
continue; // 继续下一次循环
}
else {
isStu = tmp == "stu"; // 如果 SQL 语句中包含 stu,将 isStu 设置为 true,否则设置为 false
}
}
if (ss >> tmp) // 如果 SQL 语句中包含 WHERE
{
if (tmp != "WHERE") // 如果 SQL 语句中 WHERE 后面不是条件
{
cout << "Invalid SQL!" << endl; // 输出错误信息
continue; // 继续下一次循环
}
else {
bool conti = false;
while (ss >> tmp) {
if (tmp == "Score" || tmp == "Salary") // 如果 SQL 语句中包含 Score 或 Salary
{
ss >> tmp;
if (tmp == ">=") {
ss >> limits;
if (isStu) {
for (auto it = stu.begin(); it != stu.end();) {
if (it->data < limits)
it = stu.erase(it); // 如果数据小于 limits,将该数据从 set 容器中删除
else
++it;
}
}
else {
for (auto it = employee.begin(); it != employee.end();) {
if (it->data < limits)
it = employee.erase(it); // 如果数据小于 limits,将该数据从 set 容器中删除
else
++it;
}
}
}
else if (tmp == "<=") {
ss >> limits;
if (isStu) {
for (auto it = stu.begin(); it != stu.end();) {
if (it->data > limits)
it = stu.erase(it); // 如果数据大于 limits,将该数据从 set 容器中删除
else
++it;
}
}
else {
for (auto it = employee.begin(); it != employee.end();) {
if (it->data > limits)
it = employee.erase(it); // 如果数据大于 limits,将该数据从 set 容器中删除
else
++it;
}
}
}
else if (tmp == "=") {
ss >> limits;
if (isStu) {
for (auto it = stu.begin(); it != stu.end();) {
if (it->data != limits)
it = stu.erase(it); // 如果数据不等于 limits,将该数据从 set 容器中删除
else
++it;
}
}
else {
for (auto it = employee.begin(); it != employee.end();) {
if (it->data != limits)
it = employee.erase(it); // 如果数据不等于 limits,将该数据从 set 容器中删除
else
++it;
}
}
}
else if (tmp == "<") {
ss >> limits;
if (isStu) {
for (auto it = stu.begin(); it != stu.end();) {
if (it->data >= limits)
it = stu.erase(it); // 如果数据大于等于 limits,将该数据从 set 容器中删除
else
++it;
}
}
else {
for (auto it = employee.begin(); it != employee.end();) {
if (it->data >= limits)
it = employee.erase(it); // 如果数据大于等于 limits,将该数据从 set 容器中删除
else
++it;
}
}
}
else if (tmp == ">") {
ss >> limits;
if (isStu) {
for (auto it = stu.begin(); it != stu.end();) {
if (it->data <= limits)
it = stu.erase(it); // 如果数据小于等于 limits,将该数据从 set 容器中删除
else
++it;
}
}
else {
for (auto it = employee.begin(); it != employee.end();) {
if (it->data <= limits)
it = employee.erase(it); // 如果数据小于等于 limits,将该数据从 set 容器中删除
else
++it;
}
}
}
else {
cout << "Invalid SQL!" << endl; // 输出错误信息
conti = true; // 设置 conti 为 true
continue;
}
}
else if (tmp == "Gender") // 如果 SQL 语句中包含 Gender
{
ss >> tmp;
if (tmp != "=") {
cout << "Invalid SQL!" << endl; // 输出错误信息
conti = true; // 设置 conti 为 true
continue;
}
ss >> tmp;
if (tmp == "male")
isMale = true; // 如果 SQL 语句中包含 male,将 isMale 设置为 true
else if (tmp == "female")
isMale = false; // 如果 SQL 语句中包含 female,将 isMale 设置为 false
else {
cout << "Invalid SQL!" << endl; // 输出错误信息
conti = true; // 设置 conti 为 true
continue;
}
if (isStu) {
for (auto it = stu.begin(); it != stu.end();) {
if (it->isMale != isMale)
it = stu.erase(it); // 如果数据的性别与 isMale 不同,将该数据从 set 容器中删除
else
++it;
}
}
else {
for (auto it = employee.begin(); it != employee.end();) {
if (it->isMale != isMale)
it = employee.erase(it); // 如果数据的性别与 isMale 不同,将该数据从 set 容器中删除
else
++it;
}
}
}
else if (tmp == "AND")
continue; // 如果 SQL 语句中包含 AND,继续下一次循环
else {
cout << "Invalid SQL!" << endl; // 输出错误信息
conti = true; // 设置 conti 为 true
continue;
}
}
if (conti)
continue; // 继续下一次循环
}
}
if (isStu) // 如果 SQL 语句中包含 stu
{
if (col[0])
cout << "ID ";
if (col[1])
cout << "Name ";
if (col[2])
cout << "Gender ";
if (col[3])
cout << "Score ";
cout << endl;
for (auto it = stu.begin(); it != stu.end(); ++it) {
if (col[0])
cout << it->id << " ";
if (col[1])
cout << it->name << " ";
if (col[2])
cout << (it->isMale ? "male" : "female") << " ";
if (col[3])
cout << it->data << " ";
cout << endl;
}
}
else // 如果 SQL 语句中包含 employee
{
if (col[0])
cout << "ID ";
if (col[1])
cout << "Name ";
if (col[2])
cout << "Gender ";
if (col[3])
cout << "Salary ";
cout << endl;
for (auto it = employee.begin(); it != employee.end(); ++it) {
if (col[0])
cout << it->id << " ";
if (col[1])
cout << it->name << " ";
if (col[2])
cout << (it->isMale ? "male" : "female") << " ";
if (col[3])
cout << it->data << " ";
cout << endl;
}
}
}
}
@@ -0,0 +1,32 @@
// Copyright (c) 2023 Xi Xu
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
// 递归计算表达式的值
double Evalue(const string &exp, int &pos) {
char e = exp[pos]; // 取出当前位置的字符
switch (e) // 根据字符类型进行不同的计算
{
case '+':
return Evalue(exp, ++pos) + Evalue(exp, ++pos); // 如果是加号,则计算左右两边表达式的值之和
case '-':
return Evalue(exp, ++pos) - Evalue(exp, ++pos); // 如果是减号,则计算左右两边表达式的值之差
case '*':
return Evalue(exp, ++pos) * Evalue(exp, ++pos); // 如果是乘号,则计算左右两边表达式的值之积
case '/':
return Evalue(exp, ++pos) / Evalue(exp, ++pos); // 如果是除号,则计算左右两边表达式的值之商
default:
return e - '0'; // 如果是数字,则返回该数字的值
}
}
int main() {
string exp;
cin >> exp;
int pos = 0;
cout << Evalue(exp, pos) << endl;
return 0;
}
@@ -0,0 +1,139 @@
// Copyright (c) 2023 徐丞烨,王凯钦,宋析峰,杨崇新
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
// 定义一个图类
class Graph {
private:
int n, e; // n表示图中顶点的个数,e表示图中边的个数
int **adj; // 邻接矩阵
public:
Graph(istream &in); // 构造函数,从输入流中读取图的信息
~Graph(); // 析构函数,释放邻接矩阵的内存
int getn() const {
return n;
} // 返回图中顶点的个数
void print() const; // 打印邻接矩阵
bool bfs(int u, int v) const; // 判断从顶点u到顶点v是否存在一条路径,使用广度优先搜索算法
bool dfs(int u, int v, bool *visited) const; // 判断从顶点u到顶点v是否存在一条路径,使用深度优先搜索算法
bool **warshall() const; // 计算图的传递闭包,使用Warshall算法
};
// 构造函数,从输入流in中读取图的信息
Graph::Graph(istream &in) {
in >> n >> e; // 读取顶点数和边数
adj = new int *[n]; // 动态分配邻接矩阵的内存
for (size_t i = 0; i < n; i++) {
adj[i] = new int[n];
for (size_t j = 0; j < n; j++)
adj[i][j] = 0; // 初始化邻接矩阵
}
for (size_t i = 0; i < e; i++) {
int u, v;
in >> u >> v;
adj[u - 1][v - 1]++; // 读取边的信息,更新邻接矩阵
}
}
// 析构函数,释放邻接矩阵的内存
Graph::~Graph() {
for (size_t i = 0; i < n; i++)
delete[] adj[i];
delete[] adj;
}
// 打印邻接矩阵
void Graph::print() const {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++)
cout << adj[i][j] << " ";
cout << endl;
}
}
// 判断从顶点u到顶点v是否存在一条路径,使用广度优先搜索算法
bool Graph::bfs(int u, int v) const {
if (u == v)
return true;
queue<int> q;
bool visited[n];
memset(visited, false, sizeof(visited));
q.push(u);
visited[u] = true;
while (!q.empty()) {
int w = q.front();
q.pop();
for (size_t i = 0; i < n; i++)
if (adj[w][i] && !visited[i]) {
if (i == v)
return true;
q.push(i);
visited[i] = true;
}
}
return false;
}
// 判断从顶点u到顶点v是否存在一条路径,使用深度优先搜索算法
bool Graph::dfs(int u, int v, bool *visited) const {
if (u == v)
return true;
visited[u] = true;
for (size_t i = 0; i < n; i++)
if (adj[u][i] && !visited[i])
if (dfs(i, v, visited))
return true;
return false;
}
// 计算图的传递闭包,使用Warshall算法
bool **Graph::warshall() const {
bool **rch = new bool *[n];
for (size_t i = 0; i < n; i++) {
rch[i] = new bool[n];
for (size_t j = 0; j < n; j++)
rch[i][j] = adj[i][j];
rch[i][i] = true;
}
for (size_t k = 0; k < n; k++)
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < n; j++)
rch[i][j] = rch[i][j] || (rch[i][k] && rch[k][j]);
return rch;
}
// 主函数
int main() {
ifstream fin("graph.txt"); // 打开文件
Graph g(fin); // 创建图对象
fin.close(); // 关闭文件
cout << "Adjacency matrix:" << endl;
g.print(); // 打印邻接矩阵
cout << "BFS:" << endl;
for (size_t i = 0; i < g.getn(); i++) {
for (size_t j = 0; j < g.getn(); j++)
cout << g.bfs(i, j) << " "; // 判断从顶点i到顶点j是否存在一条路径,使用广度优先搜索算法
cout << endl;
}
cout << "DFS:" << endl;
for (size_t i = 0; i < g.getn(); i++) {
for (size_t j = 0; j < g.getn(); j++) {
bool visited[g.getn()];
memset(visited, false, sizeof(visited));
cout << g.dfs(i, j, visited) << " "; // 判断从顶点i到顶点j是否存在一条路径,使用深度优先搜索算法
}
cout << endl;
}
cout << "Warshall:" << endl;
bool **rch = g.warshall(); // 计算图的传递闭包,使用Warshall算法
for (size_t i = 0; i < g.getn(); i++) {
for (size_t j = 0; j < g.getn(); j++)
cout << rch[i][j] << " ";
cout << endl;
}
return 0;
}
@@ -0,0 +1,106 @@
// Copyright (c) 2023 徐丞烨,王凯钦,宋析峰,杨崇新
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
class Graph {
private:
int n; // 图的顶点数
int **adj; // 邻接矩阵
public:
Graph(istream &in); // 构造函数,从输入流in中读取邻接矩阵
~Graph(); // 析构函数,释放邻接矩阵的内存
int tsp(); // TSP 算法,计算最短哈密顿回路
void tsp_backtrack(int k, int *path, int *visited, int &min_path); // 回溯法
int path_len(int *path, int k); // 计算路径长度
};
Graph::Graph(istream &in) {
in >> n; // 读取顶点数
adj = new int *[n]; // 动态分配二维数组
for (size_t i = 0; i < n; i++) {
adj[i] = new int[n];
}
for (size_t i = 0; i < n; i++) {
adj[i][i] = 0; // 对角线上的元素为0
for (int j = i + 1; j < n; j++) {
in >> adj[i][j]; // 读取邻接矩阵
adj[j][i] = adj[i][j]; // 邻接矩阵是对称矩阵
}
}
}
Graph::~Graph() {
for (size_t i = 0; i < n; ++i)
delete[] adj[i]; // 释放每一行的内存
delete[] adj; // 释放二维数组的内存
}
int Graph::tsp() {
int *path = new int[n]; // 存储当前的路径
int *visited = new int[n]; // 存储已经访问过的顶点
int min_path = INT_MAX; // 存储最短路径长度
// 初始化
for (int i = 0; i < n; i++) {
visited[i] = 0;
}
visited[0] = 1;
path[0] = 0;
// 回溯
tsp_backtrack(1, path, visited, min_path);
// 释放内存
delete[] path;
delete[] visited;
return min_path;
}
void Graph::tsp_backtrack(int k, int *path, int *visited, int &min_path) {
if (k == n) // 所有的顶点都已经遍历完了
{
int path_len = 0;
for (int i = 0; i < n - 1; i++) {
path_len += adj[path[i]][path[i + 1]];
}
path_len += adj[path[n - 1]][0]; // 回到起点
if (path_len < min_path) {
min_path = path_len;
}
return;
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
path[k] = i;
visited[i] = 1;
if (path_len(path, k) < min_path) // 剪枝
{
tsp_backtrack(k + 1, path, visited, min_path);
}
visited[i] = 0;
}
}
}
int Graph::path_len(int *path, int k) {
int len = 0;
for (int i = 0; i < k - 1; i++) {
len += adj[path[i]][path[i + 1]];
}
len += adj[path[k - 1]][0]; // 回到起点
return len;
}
int main() {
ifstream fin("adj.txt"); // 打开输入文件
Graph g(fin); // 创建图
fin.close(); // 关闭输入文件
cout << g.tsp() << endl; // 计算最短哈密顿回路并输出
return 0;
}
@@ -0,0 +1,80 @@
// Copyright (c) 2023 徐丞烨,王凯钦,宋析峰,杨崇新
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
class Graph {
private:
int n; // 图的顶点数
int **adj; // 邻接矩阵
public:
Graph(istream &in); // 构造函数,从输入流in中读取邻接矩阵
~Graph(); // 析构函数,释放邻接矩阵的内存
void floyd() const; // Floyd算法,计算任意两点之间的最短路径
};
Graph::Graph(istream &in) {
in >> n; // 读取顶点数
adj = new int *[n]; // 动态分配二维数组
for (size_t i = 0; i < n; i++) {
adj[i] = new int[n];
for (size_t j = 0; j < n; j++)
in >> adj[i][j]; // 读取邻接矩阵
}
}
Graph::~Graph() {
for (size_t i = 0; i < n; i++)
delete[] adj[i]; // 释放每一行的内存
delete[] adj; // 释放二维数组的内存
}
void Graph::floyd() const {
int dist[n][n]; // 存储任意两点之间的最短距离
int path[n][n]; // 存储任意两点之间的最短路径
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < n; j++) {
dist[i][j] = adj[i][j]; // 初始化最短距离
path[i][j] = j; // 初始化最短路径
}
for (size_t k = 0; k < n; k++)
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < n; j++)
if (dist[i][k] + dist[k][j] < dist[i][j]) // 如果经过k点的路径更短
{
dist[i][j] = dist[i][k] + dist[k][j]; // 更新最短距离
path[i][j] = path[i][k]; // 更新最短路径
}
for (size_t i = 0; i < n; i++) {
cout << "From " << i + 1 << ":" << endl; // 输出起点
for (size_t j = 0; j < n; j++) {
if (i == j)
continue;
cout << "To " << j + 1 << ": ";
cout << i + 1 << " "; // 输出起点
int k = path[i][j];
while (k != j) // 输出路径上的中间点
{
cout << k + 1 << " ";
k = path[k][j];
}
cout << j + 1 << endl; // 输出终点
}
cout << endl;
}
}
int main() {
// 打开输入文件
ifstream fin("adj.txt");
// 创建图
Graph g(fin);
// 关闭输入文件
fin.close();
// 计算任意两点之间的最短路径
g.floyd();
return 0;
}
@@ -0,0 +1,22 @@
// Copyright (c) 2023 Xi Xu
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
int main() {
ifstream fin("a.txt"); // 打开文件“a.txt”以读取模式
ofstream fout("b.txt"); // 打开文件“b.txt”以写入模式
string line;
while (getline(fin, line)) // 从文件“a.txt”中读取一行到 line 中
{
for (char &c : line) // 遍历 line 中的每个字符
if (c == '(' || c == ')' || c == ',') // 如果字符是“(”或“)”或“,”
c = ' '; // 将字符替换为空格
fout << line << endl; // 将 line 写入文件“b.txt”中并换行
}
fin.close(); // 关闭文件“a.txt”
fout.close(); // 关闭文件“b.txt”
return 0;
}
@@ -0,0 +1,102 @@
// Copyright (c) 2023 Xi Xu
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
// 同编程作业 1
double Evalue(const string &exp, int &pos) {
char e = exp[pos];
switch (e) {
case '+':
return Evalue(exp, ++pos) + Evalue(exp, ++pos);
case '-':
return Evalue(exp, ++pos) - Evalue(exp, ++pos);
case '*':
return Evalue(exp, ++pos) * Evalue(exp, ++pos);
case '/':
return Evalue(exp, ++pos) / Evalue(exp, ++pos);
default:
return e - '0';
}
}
// 定义二叉树节点结构体
struct Node {
int data; // 节点数据
Node *left; // 左子节点指针
Node *right; // 右子节点指针
Node(int d, Node *l = nullptr, Node *r = nullptr) : data(d), left(l), right(r) {}
};
// 定义二叉树类型别名
using Tree = Node *;
// 根据表达式构建二叉树
Tree buildTree(const string &exp, int &pos) {
char e = exp[pos]; // 获取当前字符
switch (e) {
case '+':
case '-':
case '*':
case '/': {
Tree t = new Node(e); // 创建一个新节点
t->left = buildTree(exp, ++pos); // 递归构建左子树
t->right = buildTree(exp, ++pos); // 递归构建右子树
return t;
}
default:
return new Node(e - '0'); // 创建一个新节点,存储当前数字字符对应的数字
}
}
// 判断节点是否为运算符
bool isOperator(const Tree t) {
return t->data == '+' || t->data == '-' || t->data == '*' || t->data == '/';
}
// 判断两个运算符的优先级关系
bool lowerOrEqualPrecedence(const char op1, const char op2) {
if (op1 == '+' || op1 == '-')
return true;
if (op1 == '*' || op1 == '/')
return op2 == '*' || op2 == '/';
return false;
}
// 中序遍历二叉树并输出表达式
void print(const Tree t) {
if (t == nullptr)
return;
if (isOperator(t)) // 如果当前节点是运算符
{
bool leftParen = isOperator(t->left) && lowerOrEqualPrecedence(t->left->data, t->data); // 判断左子节点是否需要加括号
bool rightParen = isOperator(t->right) && lowerOrEqualPrecedence(t->right->data, t->data); // 判断右子节点是否需要加括号
if (leftParen)
cout << "("; // 输出左括号
print(t->left); // 递归输出左子树
if (leftParen)
cout << ")"; // 输出右括号
cout << (char)t->data; // 输出当前运算符
if (rightParen)
cout << "("; // 输出左括号
print(t->right); // 递归输出右子树
if (rightParen)
cout << ")"; // 输出右括号
}
else
cout << t->data; // 如果当前节点是数字,直接输出
}
int main() {
string exp;
cin >> exp;
int pos = 0;
cout << Evalue(exp, pos) << endl;
pos = 0;
Tree t = buildTree(exp, pos);
print(t);
cout << endl;
return 0;
}
@@ -0,0 +1,104 @@
// Copyright (c) 2023 Xi Xu
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
map<char, int> priority{ { '+', 1 }, { '-', 1 }, { '*', 2 }, { '/', 2 } };
double Evalue(const string &s) {
stack<double> num; // 存储数字的栈
stack<char> op; // 存储运算符的栈
int i = 0;
while (i < s.size()) {
if (s[i] == ' ') // 如果是空格则跳过
{
i++;
continue;
}
if (isdigit(s[i])) // 如果是数字则将其转换为 double 类型并压入数字栈
{
double temp = 0;
while (i < s.size() && isdigit(s[i])) {
temp = temp * 10 + s[i] - '0';
i++;
}
num.push(temp);
}
else if (s[i] == '(') // 如果是左括号则将其压入运算符栈
{
op.push(s[i]);
i++;
}
else if (s[i] == ')') // 如果是右括号则进行运算
{
while (op.top() != '(') // 直到遇到左括号为止
{
double b = num.top(); // 取出数字栈的栈顶元素
num.pop(); // 弹出数字栈的栈顶元素
double a = num.top(); // 取出数字栈的栈顶元素
num.pop(); // 弹出数字栈的栈顶元素
char c = op.top(); // 取出运算符栈的栈顶元素
op.pop(); // 弹出运算符栈的栈顶元素
if (c == '+') // 进行加法运算
num.push(a + b);
else if (c == '-') // 进行减法运算
num.push(a - b);
else if (c == '*') // 进行乘法运算
num.push(a * b);
else if (c == '/') // 进行除法运算
num.push(a / b);
}
op.pop(); // 弹出左括号
i++;
}
else // 如果是运算符则进行运算
{
while (!op.empty() && op.top() != '(' && priority[op.top()] >= priority[s[i]]) // 如果运算符栈不为空且栈顶元素不是左括号且当前运算符的优先级小于等于栈顶运算符的优先级
{
double b = num.top(); // 取出数字栈的栈顶元素
num.pop(); // 弹出数字栈的栈顶元素
double a = num.top(); // 取出数字栈的栈顶元素
num.pop(); // 弹出数字栈的栈顶元素
char c = op.top(); // 取出运算符栈的栈顶元素
op.pop(); // 弹出运算符栈的栈顶元素
if (c == '+') // 进行加法运算
num.push(a + b);
else if (c == '-') // 进行减法运算
num.push(a - b);
else if (c == '*') // 进行乘法运算
num.push(a * b);
else if (c == '/') // 进行除法运算
num.push(a / b);
}
op.push(s[i]); // 将当前运算符压入运算符栈
i++;
}
}
while (!op.empty()) // 如果运算符栈不为空则进行运算
{
double b = num.top(); // 取出数字栈的栈顶元素
num.pop(); // 弹出数字栈的栈顶元素
double a = num.top(); // 取出数字栈的栈顶元素
num.pop(); // 弹出数字栈的栈顶元素
char c = op.top(); // 取出运算符栈的栈顶元素
op.pop(); // 弹出运算符栈的栈顶元素
if (c == '+') // 进行加法运算
num.push(a + b);
else if (c == '-') // 进行减法运算
num.push(a - b);
else if (c == '*') // 进行乘法运算
num.push(a * b);
else if (c == '/') // 进行除法运算
num.push(a / b);
}
return num.top(); // 返回数字栈的栈顶元素
}
int main() {
string s;
getline(cin, s);
cout << Evalue(s) << endl;
return 0;
}
@@ -0,0 +1,84 @@
// Copyright (c) 2023 Xi Xu
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
// 定义记录结构体
struct Record {
int id; // 学号
string name; // 姓名
bool isMale; // 性别
double score; // 成绩
Record(int id = 0, string name = "", bool isMale = true, double score = 0) : id(id), name(name), isMale(isMale), score(score) {}
};
// 定义比较函数
struct cmp {
bool operator()(const Record &a, const Record &b) const {
return a.id < b.id;
}
};
int main() {
// 定义记录集合
set<Record, cmp> records;
// 读取文件
ifstream fin("E:\\OneDrive\\Code\\C++\\data.txt");
string ignore;
getline(fin, ignore);
// 逐行读取文件
while (!fin.eof()) {
int id;
string name, gender;
bool isMale;
double score;
fin >> id >> name >> gender >> score;
// 判断性别
if (gender == "男")
isMale = true;
else
isMale = false;
// 添加记录
records.insert(Record(id, name, isMale, score));
}
fin.close();
// 定义列标志数组
bool col[4];
for (bool &b : col)
b = false;
double floorscore;
char t;
// 读取列标志和分数
while (cin >> t, isdigit(t))
col[t - '0' - 1] = true;
cin >> floorscore;
// 输出表头
if (col[0])
cout << "学号\t";
if (col[1])
cout << "姓名\t";
if (col[2])
cout << "性别\t";
if (col[3])
cout << "成绩" << endl;
// 输出符合条件的记录
for (const Record &r : records)
if (r.score >= floorscore) {
if (col[0])
cout << r.id << "\t";
if (col[1])
cout << r.name << "\t";
if (col[2]) {
if (r.isMale)
cout << "男\t";
else
cout << "女\t";
}
if (col[3])
cout << r.score;
cout << endl;
}
return 0;
}
@@ -0,0 +1,57 @@
// Copyright (c) 2023 Xi Xu
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
class Graph // 定义 Graph 类
{
private:
int n, e; // n 表示节点数,e 表示边数
int **adj; // 邻接矩阵
public:
Graph(istream &in); // 构造函数
int cnt2(); // 计算邻接矩阵的平方中边的数量
};
Graph::Graph(istream &in) // 构造函数实现
{
in >> n >> e; // 读入节点数和边数
adj = new int *[n]; // 动态分配邻接矩阵内存
for (size_t i = 0; i < n; i++) // 初始化邻接矩阵
{
adj[i] = new int[n];
for (size_t j = 0; j < n; j++)
adj[i][j] = 0;
}
for (size_t i = 0; i < e; i++) // 读入边
{
int u, v;
in >> u >> v;
adj[u - 1][v - 1]++; // 在邻接矩阵中标记边
}
}
int Graph::cnt2() // 计算长度为 2 的通路数
{
int adj2[n][n]; // 定义邻接矩阵的平方
memset(adj2, 0, sizeof(adj2)); // 将邻接矩阵的平方初始化为 0
for (int i = 0; i < n; i++) // 计算邻接矩阵的平方
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
adj2[i][j] += adj[i][k] * adj[k][j];
int cnt = 0; // 定义边的数量
for (size_t i = 0; i < n; i++) // 统计边的数量
for (size_t j = 0; j < n; j++)
cnt += adj2[i][j];
return cnt; // 返回边的数量
}
int main() {
ifstream fin("E:\\OneDrive\\Code\\C++\\graph.txt"); // 打开文件
Graph g(fin); // 创建 Graph 对象 g
cout << g.cnt2() << endl; // 输出 g 中的长度为 2 的通路数
return 0;
}
@@ -0,0 +1,86 @@
// Copyright (c) 2023 Xi Xu
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
class Graph // 定义 Graph 类
{
private:
int n, e; // n 表示节点数,e 表示边数
int **adj; // 邻接矩阵
public:
Graph(istream &in); // 构造函数
~Graph(); // 析构函数
int getn() { return n; } // 返回节点数
void dfs(int v = 0, bool *visited = nullptr); // 深度优先搜索
};
Graph::Graph(istream &in) // 构造函数实现
{
in >> n >> e; // 读入节点数和边数
adj = new int *[n]; // 动态分配邻接矩阵内存
for (size_t i = 0; i < n; i++) // 初始化邻接矩阵
{
adj[i] = new int[n];
for (size_t j = 0; j < n; j++)
adj[i][j] = 0;
}
for (size_t i = 0; i < e; i++) // 读入边
{
int u, v;
in >> u >> v;
adj[u - 1][v - 1]++; // 在邻接矩阵中标记边
}
}
Graph::~Graph() // 析构函数实现
{
for (size_t i = 0; i < n; i++) // 释放邻接矩阵内存
delete[] adj[i];
delete[] adj;
}
void Graph::dfs(int v, bool *visited) // 深度优先搜索实现
{
visited[v] = true; // 标记节点为已访问
for (size_t i = 0; i < n; i++) // 遍历邻接矩阵
if (adj[v][i] && !visited[i]) // 如果存在边且节点未被访问
dfs(i, visited); // 递归访问节点
}
bool alltrue(bool *arr, int n) // 判断数组中所有元素是否为 true
{
for (size_t i = 0; i < n; i++)
if (!arr[i])
return false;
return true;
}
int main() {
ifstream fin("graph.txt"); // 打开文件
Graph g(fin); // 创建 Graph 对象 g
bool visited[g.getn()], outputed[g.getn()]; // 定义 visited 和 outputed 数组
for (size_t i = 0; i < g.getn(); i++) // 初始化 visited 和 outputed 数组
{
visited[i] = false;
outputed[i] = false;
}
int i = -1; // 初始化 i
while (!alltrue(outputed, g.getn())) // 如果 outputed 数组中有 false
{
while (visited[++i]) // 找到第一个未被访问的节点
;
g.dfs(i, visited); // 从该节点开始深度优先搜索
for (size_t i = 0; i < g.getn(); i++) // 遍历 visited 数组
if (visited[i] && !outputed[i]) // 如果节点被访问且未输出
{
cout << i + 1 << " "; // 输出节点编号
outputed[i] = true; // 标记节点为已输出
}
cout << endl;
}
return 0;
}
@@ -0,0 +1,66 @@
// Copyright (c) 2023 Xi Xu
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
class Graph // 完全图类
{
private:
int n; // 节点数
int **w; // 每条边的权值
public:
Graph(istream &in); // 构造函数,从输入流中读取图的信息
~Graph(); // 析构函数,释放内存
int tsp(); // 求解 TSP 问题
};
Graph::Graph(istream &in) {
in >> n; // 读取节点数
w = new int *[n];
for (size_t i = 0; i < n; i++) {
w[i] = new int[n];
}
for (size_t i = 0; i < n; i++) // 读取每条边的权值
{
w[i][i] = 0; // 对角线上的元素为 0
for (int j = i + 1; j < n; j++) {
in >> w[i][j]; // 读取上三角元素
w[j][i] = w[i][j]; // 下三角元素与上三角元素相等
}
}
}
Graph::~Graph() {
for (size_t i = 0; i < n; i++)
delete[] w[i];
delete[] w;
}
int Graph::tsp() // Graph 类的求解 TSP 问题的函数
{
int p[n]; // 存储节点的排列
for (int i = 0; i < n; i++)
p[i] = i; // 初始排列为 0, 1, ..., n-1
int min = INT_MAX; // 存储最小路径长度
do // 枚举所有可能的排列
{
int sum = 0; // 计算当前排列的路径长度
for (int i = 0; i < n - 1; i++)
sum += w[p[i]][p[i + 1]];
sum += w[p[n - 1]][p[0]];
if (sum < min) // 更新最小路径长度
min = sum;
} while (next_permutation(p, p + n)); // STL 中的排列生成函数
return min; // 返回最小路径长度
}
int main() {
ifstream fin("graph.txt"); // 打开输入文件
Graph g(fin); // 创建 Graph 类的对象
fin.close(); // 关闭输入文件
cout << g.tsp() << endl; // 求解 TSP 问题
return 0;
}
@@ -0,0 +1,127 @@
// Copyright (c) 2023 徐丞烨,王凯钦,宋析峰,杨崇新
// SPDX-License-Identifier: GPL-3.0-or-later
#include <bits/stdc++.h>
using namespace std;
class Graph {
private:
int n, e;
int **adj;
public:
Graph(istream &in);
~Graph();
void print() const;
bool isEulerian() const;
void dfs(int u, bool *visited, int v = 0, int w = 0) const;
bool isBridge(int u, int v) const;
void fleury() const;
};
Graph::Graph(istream &in) {
in >> n >> e;
adj = new int *[n];
for (size_t i = 0; i < n; i++) {
adj[i] = new int[n];
for (size_t j = 0; j < n; j++)
adj[i][j] = 0;
}
for (size_t i = 0; i < e; i++) {
int u, v;
in >> u >> v;
adj[u - 1][v - 1]++;
}
}
Graph::~Graph() {
for (size_t i = 0; i < n; i++)
delete[] adj[i];
delete[] adj;
}
void Graph::print() const {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++)
cout << adj[i][j] << " ";
cout << endl;
}
}
bool Graph::isEulerian() const {
for (size_t i = 0; i < n; i++) {
int sum = 0;
for (size_t j = 0; j < n; j++)
sum += adj[i][j];
for (size_t j = 0; j < n; j++)
sum -= adj[j][i];
if (sum != 0)
return false;
}
return true;
}
void Graph::dfs(int u, bool *visited, int v, int w) const {
visited[u] = true;
for (size_t i = 0; i < n; i++)
if (adj[u][i] && !visited[i] && !(u == v && i == w))
dfs(i, visited, v, w);
}
bool Graph::isBridge(int u, int v) const {
if (adj[u][v] == 0)
return false;
int cnt = 0;
bool visited[n];
memset(visited, false, sizeof(visited));
for (size_t i = 0; i < n; i++)
if (!visited[i]) {
dfs(i, visited);
cnt++;
}
memset(visited, false, sizeof(visited));
for (size_t i = 0; i < n; i++)
if (!visited[i]) {
dfs(i, visited, u, v);
cnt--;
}
return cnt < 0;
}
void Graph::fleury() const {
int copyadj[n][n];
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < n; j++)
copyadj[i][j] = adj[i][j];
int u = 0;
while (true) {
cout << u + 1 << " ";
bool flag = false;
for (size_t v = 0; v < n; v++)
if (copyadj[u][v] && !isBridge(u, v)) {
copyadj[u][v]--;
u = v;
flag = true;
break;
}
if (!flag)
break;
}
}
int main() {
ifstream fin("graph.txt");
Graph g(fin);
fin.close();
cout << "Adjacency matrix:" << endl;
g.print();
bool is = g.isEulerian();
if (g.isEulerian()) {
cout << "The graph is Eulerian." << endl;
g.fleury();
}
else
cout << "The graph is not Eulerian." << endl;
return 0;
}
@@ -0,0 +1,6 @@
5
0 1 3 8 1000
1000 0 1000 1 1000
1000 4 0 1000 1000
1000 1000 1 0 3
1000 1000 1000 1000 0
@@ -0,0 +1,4 @@
23 + 45 = 68
20 + (13 - 10) = 23
(-4.6 - 12) + 2.4 ^ 2 * 5 = 12.2
54 / (-3 + (9 - 3)) = 18
@@ -0,0 +1,4 @@
1001 Xiao male 1000
1002 Hong female 1550
1003 Li male 1865
1004 Ming female 1691
@@ -0,0 +1,8 @@
5 7
1 2
1 3
2 3
2 4
3 5
5 1
5 4
@@ -0,0 +1,4 @@
add(23, 45)
add(20, sub(13, 10))
add(sub(neg(4.6), 12), muti(doubleMe(2.4), 5))
div(54, add(-3, sub(9, 3)))
@@ -0,0 +1,4 @@
1001 YCX male 100
1002 WKQ female 99
1003 SYF male 1000
1004 XCY female 0
@@ -0,0 +1,6 @@
5
3 1 5 8
6 7 9
4 2
3