PTA(浙大数据结构,c语言)

01-复杂度1 最大子列和问题node

给定K个整数组成的序列{ N​1​​, N​2​​, ..., N​K​​ },“连续子列”被定义为{ N​i​​, N​i+1​​, ..., N​j​​ },其中 1。“最大子列和”则被定义为全部连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。git

本题旨在测试各类不一样的算法在各类数据状况下的表现。各组测试数据特色以下:算法

数据1:与样例等价,测试基本正确性;数组

数据2:102个随机整数;微信

数据3:103个随机整数;网络

数据4:104个随机整数;app

数据5:105个随机整数;less

输入格式:dom

输入第1行给出正整数K (≤);第2行给出K个整数,其间以空格分隔。ide

输出格式:

在一行中输出最大子列和。若是序列中全部整数皆为负数,则输出0。

输入样例:

6

-2 11 -4 13 -5 -2

输出样例:

20

 1 #include <stdio.h>
 2 
 3 //分而治之
 4 int Max3( int A, int B, int C );  5 int DivideAndConquer( int List[], int left, int right );  6 int MaxSubseqSum3( int List[], int N );  7 
 8 int main()  9 { 10     int arr[100000]; 11     int n; 12     scanf("%d",&n); 13     for (int i = 0; i < n; ++i) 14  { 15         scanf("%d",&arr[i]); 16  } 17     printf("%d",MaxSubseqSum3(arr, n)); 18     return 0; 19 } 20 
21 int Max3( int A, int B, int C ) 22 { /* 返回3个整数中的最大值 */
23     return A > B ? A > C ? A : C : B > C ? B : C; 24 } 25  
26 int DivideAndConquer( int List[], int left, int right ) 27 { /* 分治法求List[left]到List[right]的最大子列和 */
28     int MaxLeftSum, MaxRightSum; /* 存放左右子问题的解 */
29     int MaxLeftBorderSum, MaxRightBorderSum; /*存放跨分界线的结果*/
30  
31     int LeftBorderSum, RightBorderSum; 32     int center, i; 33  
34     if( left == right )  { /* 递归的终止条件,子列只有1个数字 */
35         if( List[left] > 0 )  return List[left]; 36         else return 0; 37  } 38  
39     /* 下面是"分"的过程 */
40     center = ( left + right ) / 2; /* 找到中分点 */
41     /* 递归求得两边子列的最大和 */
42     MaxLeftSum = DivideAndConquer( List, left, center ); 43     MaxRightSum = DivideAndConquer( List, center+1, right ); 44  
45     /* 下面求跨分界线的最大子列和 */
46     MaxLeftBorderSum = 0; LeftBorderSum = 0; 47     for( i=center; i>=left; i-- ) { /* 从中线向左扫描 */
48         LeftBorderSum += List[i]; 49         if( LeftBorderSum > MaxLeftBorderSum ) 50             MaxLeftBorderSum = LeftBorderSum; 51     } /* 左边扫描结束 */
52  
53     MaxRightBorderSum = 0; RightBorderSum = 0; 54     for( i=center+1; i<=right; i++ ) { /* 从中线向右扫描 */
55         RightBorderSum += List[i]; 56         if( RightBorderSum > MaxRightBorderSum ) 57             MaxRightBorderSum = RightBorderSum; 58     } /* 右边扫描结束 */
59  
60     /* 下面返回"治"的结果 */
61     return Max3( MaxLeftSum, MaxRightSum, MaxLeftBorderSum + MaxRightBorderSum ); 62 } 63  
64 int MaxSubseqSum3( int List[], int N ) 65 { /* 保持与前2种算法相同的函数接口 */
66     return DivideAndConquer( List, 0, N-1 ); 67 }

 

 
 1 #include <stdio.h>
 2 
 3 //在线处理
 4 int MaxSubSeqSum(int a[], int k)  5 {  6     int ThisSum, MaxSum;  7     ThisSum = MaxSum = 0;  8     for(int i=0; i<k; ++i){  9         ThisSum += a[i]; 10         if(ThisSum > MaxSum) 11             MaxSum = ThisSum; 12         else if(ThisSum < 0) 13             ThisSum = 0; 14  } 15     return MaxSum; 16 } 17 int main( ) { 18     
19     const int N = 100001; 20     int a[N]; 21     int k = 0; 22     scanf("%d",&k); 23     for(int i=0; i<k; ++i) 24         scanf("%d",&a[i]); 25     printf("%d\n",MaxSubSeqSum(a,k)); 26     
27     return 0; 28 }

01-复杂度2 Maximum Subsequence Sum

Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A continuous subsequence is defined to be { N​i​​, N​i+1​​, ..., N​j​​ } where 1. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10

-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4

 
 1 #include <stdio.h>
 2 #define N 100000
 3 void max_sub_sum(int arr[], int n)  4 {  5     int this_sum = 0, max_sum = -1;  6     int first_num, last_num;  7     int index_first = 0; //第一个元素下标
 8     for (int i = 0; i < n; ++i)  9  { 10         this_sum += arr[i]; 11         if (this_sum > max_sum)//元素所有为负数进不来
12         {    //产生最大值,第一个元素,最后一个元素是肯定的
13             max_sum = this_sum; //最大值
14             first_num = arr[index_first];//第一个元素 
15             last_num = arr[i];//最后一个元素 
16  } 17         else if (this_sum < 0) 18  { 19             this_sum = 0; 20             index_first = i+1; //更新第一个元素的下标
21  } 22  } 23     if(max_sum == -1) printf("0 %d %d\n", arr[0], arr[n-1]); 24     else printf("%d %d %d\n", max_sum, first_num, last_num); 25 } 26 
27 int main() 28 { 29     int arr[N] = {0}; 30     int n; 31     scanf("%d", &n); 32     for (int i = 0; i < n; ++i) 33  { 34         scanf("%d", &arr[i]); 35  } 36  max_sub_sum(arr, n); 37     return 0; 38 }

01-复杂度3 二分查找

本题要求实现二分查找算法。

函数接口定义:

Position BinarySearch( List L, ElementType X );

其中List结构定义以下:

typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存线性表中最后一个元素的位置 */ };

L是用户传入的一个线性表,其中ElementType元素能够经过>、=、<进行比较,而且题目保证传入的数据是递增有序的。函数BinarySearch要查找X在Data中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,不然返回一个特殊的失败标记NotFound。

裁判测试程序样例:

#include <stdio.h> #include <stdlib.h>
#define MAXSIZE 10
#define NotFound 0 typedef int ElementType; typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存线性表中最后一个元素的位置 */ }; List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */ Position BinarySearch( List L, ElementType X ); int main() { List L; ElementType X; Position P; L = ReadInput(); scanf("%d", &X); P = BinarySearch( L, X ); printf("%d\n", P); return 0; } /* 你的代码将被嵌在这里 */

输入样例1:

5

12 31 55 89 101

31

输出样例1:

2

输入样例2:

3

26 78 233

31

输出样例2:

0

 1 Position BinarySearch( List L, ElementType X )  2 {  3     Position position = NotFound;  4     Position left = 1;  5     Position right = L->Last;  6 
 7     while(left <= right){  8         Position mid = (left+right)/2;  9         if(L->Data[mid] > X){ 10             right = mid - 1; 11  } 12         else if(L->Data[mid]<X){ 13             left = mid + 1; 14  } 15         else{ 16             position = mid; 17             break; 18  } 19  } 20     return position; 21 }

02-线性结构1 两个有序链表序列的合并

本题要求实现一个函数,将两个链表表示的递增整数序列合并为一个非递减的整数序列。

函数接口定义:

List Merge( List L1, List L2 );

其中List结构定义以下:

typedef struct Node *PtrToNode; struct Node { ElementType Data; /* 存储结点数据 */ PtrToNode Next; /* 指向下一个结点的指针 */ }; typedef PtrToNode List; /* 定义单链表类型 */

L1和L2是给定的带头结点的单链表,其结点存储的数据是递增有序的;函数Merge要将L1和L2合并为一个非递减的整数序列。应直接使用原序列中的结点,返回归并后的带头结点的链表头指针。

裁判测试程序样例:

#include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct Node *PtrToNode; struct Node { ElementType Data; PtrToNode Next; }; typedef PtrToNode List; List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表;空链表将输出NULL */ List Merge( List L1, List L2 ); int main() { List L1, L2, L; L1 = Read(); L2 = Read(); L = Merge(L1, L2); Print(L); Print(L1); Print(L2); return 0; } /* 你的代码将被嵌在这里 */

输入样例:

3

1 3 5

5

2 4 6 8 10

输出样例:

1 2 3 4 5 6 8 10

NULL

NULL

 1 List Merge( List L1, List L2 )  2 {  3     List pa,pb,pc,L;  //返回L
 4     L = (List)malloc(sizeof(struct Node));  5     pa=L1->Next;  //传进来的2个带头结点的链表L1,L2
 6     pb=L2->Next;  7     pc = L;  //新链表头指针赋值
 8     while(pa && pb)  9  { 10         if(pa->Data <= pb->Data) 11  { 12             pc->Next = pa; //a前插 
13             pc = pa;       //更新c指针
14             pa = pa->Next; //更新a指针
15  } 16         else  
17  { 18             pc->Next = pb; //b前插 
19             pc = pb;       //更新c指针
20             pb = pb->Next; //更新b指针 
21  } 22  } 23     pc->Next = pa ? pa : pb;//连接剩余结点 
24     L1->Next = NULL;   //按题目要求链表L1,L2置空
25     L2->Next = NULL; 26     return L; 27 }

02-线性结构2 一元多项式的乘法与加法运算

设计函数分别求两个一元多项式的乘积与和。

输入格式:

输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

输出格式:

输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。

输入样例:

4 3 4 -5 2  6 1  -2 0

3 5 20  -7 4  3 1

输出样例:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1

5 20 -4 4 -5 2 9 1 -2 0

 1 #include <stdio.h>
 2 #include <malloc.h>
 3 
 4 //结点
 5 typedef struct Node *List;  6 struct Node{  7     int coe;  //系数 
 8     int exp;   //指数 
 9  List Next;  10 };  11 
 12 //读入链表 
 13 List Read()  14 {  15     List head = NULL, L = NULL;  16     int n;  17     scanf("%d", &n);//n个结点
 18     
 19     for(int i=0; i<n; i++)  20  {  21         List p = (List)malloc(sizeof(struct Node));  22         scanf("%d %d", &p->coe, &p->exp);  23         p->Next = NULL;  //新结点
 24         
 25         if(i == 0) head = L = p; //链表第一个结点
 26         else{  27             L->Next = p; //链入链表
 28             L = L->Next; //链表指针更新
 29  }  30  }  31     return head;  32 }  33 
 34 //加法运算 
 35 List addition(List L1,List L2)  36 {  37  List head, add;  38     head = add = (List)malloc(sizeof(struct Node));  39     head->Next = NULL; //头结点(为了排序调用)
 40     
 41     while(L1 && L2)  42  {  43         List p = (List)malloc(sizeof(struct Node));  44         p->Next = NULL;  45         
 46         if(L1->exp == L2->exp){ //指数相等 
 47             p->coe = L1->coe + L2->coe; //系数相加
 48             p->exp = L1->exp; //指数赋值
 49             L1 = L1->Next; //更新L1
 50             L2 = L2->Next; //更新L2
 51         }else if(L1->exp < L2->exp){//L2结点指数大
 52             p->coe = L2->coe; //L2结点系数赋值
 53             p->exp = L2->exp; //指数赋值
 54             L2 = L2->Next;    //更新L2
 55         }else {             // L1结点指数大
 56             p->coe = L1->coe; //L1 结点系数赋值
 57             p->exp = L1->exp; //指数赋值
 58             L1 = L1->Next;  //更新L1
 59  }  60         
 61         add->Next = p;  62         add = add->Next;  63  }  64     if(L1)  // 若L1不等于NULL, 将剩下结点加入其后, 不影响原链表 
 65         add->Next = L1;  66     else if(L2)  // 同理
 67         add->Next = L2;  68     List ret = head->Next;  69     free(head);  70     return ret;  71 }  72 
 73 //乘法运算 
 74 List multiplication(List L1,List L2){  75     
 76     List mul = NULL, head = NULL, tL2 = L2;  77     
 78     for(; L1; L1 = L1->Next)  79  {  80         for(L2 = tL2; L2; L2 = L2->Next)  81  {  82             List p = (List)malloc(sizeof(struct Node));  83             p->Next = NULL;  84             p->coe = L1->coe * L2->coe;  // 系数相乘
 85             p->exp = L1->exp + L2->exp;  // 指数相加
 86             if(mul == NULL) head = mul = p;  87             else{  88                 head = addition(p, mul); //结点排序 
 89                 mul = head; // 从新肯定开头 
 90  }  91  }  92  }  93     
 94     return head;  95 }  96 
 97 //打印
 98 void Print(List L)  99 { 100     int flag = 1; 101     while(L) 102  { 103         if(!flag && L->coe)//系数不为0
104             printf(" "); 105         if(L->coe){ //系数为0不输出 
106             printf("%d %d",L->coe,L->exp); 107             flag =0; 108  } 109         L = L->Next; 110  } 111     if(flag) //空链表
112         printf("0 0"); 113     printf("\n"); 114 } 115 
116 int main() 117 { 118  List L1,L2,add,mul; 119     L1 = Read(); //链表L1
120     L2 = Read(); //链表L2
121     add = addition(L1,L2); 122     mul = multiplication(L1,L2); 123     Print(mul); //打印乘法结果
124     Print(add); //打印加法结果
125     return 0; 126 }
 1 #include <stdio.h>
 2 #include <malloc.h>
 3 // 结点
 4 typedef struct PolyNode *Polynomial;  5 struct PolyNode {  6     int coef;  7     int expon;  8  Polynomial link;  9 };  10 // 0.0
 11 void DestroyPoly(Polynomial* p){  12     while(*p)  13  {  14         Polynomial t = *p;  15         *p = (*p)->link;  16         free(t);  17  }  18 }  19 // 0.1
 20 void Attach( int c, int e, Polynomial *pRear )  21 {  22  Polynomial P;  23     P = (Polynomial)malloc(sizeof(struct PolyNode));  24     P->coef = c;    /* 对新结点赋值 */  
 25     P->expon = e;  26     P->link = NULL;  27     
 28     (*pRear)->link = P;  /* 新结点插到pRear后面 */  
 29     *pRear = P; /* 修改pRear值 */ 
 30 }  31 // 1.
 32 Polynomial ReadPoly()  33 {  34  Polynomial P, Rear, t;  35     int c, e, N;  36     scanf("%d", &N);  37     /* 头结点 */ 
 38     P = Rear = (Polynomial)malloc(sizeof(struct PolyNode));  39     Rear->link = NULL;  40     while ( N-- )  41  {  42         scanf("%d %d", &c, &e);  43         Attach(c, e, &Rear);  44  }  45     t = P;  46     P = P->link;  47     free(t);  /* 删除临时生成的头结点 */ 
 48     return P;  49 }  50 //2.
 51 Polynomial Add( Polynomial P1, Polynomial P2 )  52 {  53  Polynomial P, t1, t2, Rear, t;  54     int c, e;  55     t1 = P1;  56     t2 = P2;  57     P = Rear = (Polynomial)malloc(sizeof(struct PolyNode));  58     Rear->link = NULL;  59     
 60     while (t1 && t2)  61  {  62         if (t1->expon == t2->expon) {  63             e = t1->expon;  64             c = t1->coef + t2->coef;  65             if(c) Attach(c, e, &Rear);  66             t1 = t1->link;  67             t2 = t2->link;  68  }  69         else if (t1->expon > t2->expon) {  70             e = t1->expon;  71             c = t1->coef;  72             if(c) Attach(c, e, &Rear);  73             t1 = t1->link;  74  }  75         else {  76             e = t2->expon;  77             c = t2->coef;  78             if(c) Attach(c, e, &Rear);  79             t2 = t2->link;  80  }  81  }  82     
 83     while (t1) {  84         e = t1->expon;  85         c = t1->coef;  86         if(c) Attach(c, e, &Rear);  87         t1 = t1->link;  88  }  89     while (t2) {  90         e = t2->expon;  91         c = t2->coef;  92         if(c) Attach(c, e, &Rear);  93         t2 = t2->link;  94  }  95     
 96     t = P;  97     P = P->link;  98     free(t);  /* 删除临时生成的头结点 */ 
 99     return P; 100 } 101 //3.0
102 Polynomial Mult( Polynomial P1, Polynomial P2 ) 103 { 104  Polynomial P, Mul, t1, t2, t; 105     int c, e; 106 
107     if (!P1 || !P2) return NULL; 108  
109     t1 = P1; 110     t2 = P2; 111     P = Mul = NULL; 112     
113     for(; t1; t1 = t1->link) 114  { 115         for (t2 = P2; t2;  t2 = t2->link) 116  { 117             e = t1->expon + t2->expon; 118             c = t1->coef * t2->coef; 119             if(c) 120  { 121                 t = (Polynomial)malloc(sizeof(struct PolyNode)); 122                 t->coef = c; 123                 t->expon = e; 124                 t->link = NULL; 125                 
126                 if(Mul == NULL) P = Mul = t; 127                 else{ 128                     P = Add(t, Mul); 129                     free(t); 130                     DestroyPoly(&Mul); 131                     Mul = P; 132  } 133  } 134  } 135  } 136 
137     return P; 138 } 139 
140 #ifdef N 141 //3.1
142 Polynomial Mult( Polynomial P1, Polynomial P2 ) 143 { 144  Polynomial P, Rear, t1, t2, t; 145     int c, e; 146 
147     if (!P1 || !P2) return NULL; 148  
149     t1 = P1; 150     t2 = P2; 151     P = Rear = (Polynomial)malloc(sizeof(struct PolyNode)); 152     Rear->link = NULL; // P->link = NULL;
153     
154     while (t2) /* 先用P1的第1项乘以P2,获得P */ 
155  { 156         Attach(t1->coef*t2->coef, t1->expon+t2->expon, &Rear); 157         t2 = t2->link; 158  } 159     
160     t1 = t1->link;/* 从第2项开始逐项相乘 */ 
161     for(; t1; t1 = t1->link) 162  { 163         Rear = P; 164         for (t2 = P2; t2;  t2 = t2->link) 165  { 166             e = t1->expon + t2->expon; 167             c = t1->coef * t2->coef; 168             while (Rear->link && Rear->link->expon > e)//指数大 
169                 Rear = Rear->link; 170             if (Rear->link && Rear->link->expon == e)//指数相等 
171  { 172                 if (Rear->link->coef + c) /* 系数和大于0 */  
173                     Rear->link->coef += c; 174                 else {              /* 和等于0 */    
175                     t = Rear->link; 176                     Rear->link = t->link; 177                     free(t); 178  } 179  } 180             else {                                 //指数小
181                 t = (Polynomial)malloc(sizeof(struct PolyNode)); 182                 t->coef = c; 183                 t->expon = e; 184                 t->link = Rear->link; 185                 Rear->link = t; 186                 Rear = Rear->link; 187  } 188  } 189  } 190     t = P; 191     P = P->link; 192     free(t);  /* 删除临时生成的头结点 */ 
193     return P; 194 } 195 #endif
196 //4.
197 void PrintPoly( Polynomial P ) 198 {   /* 输出多项式 */  
199     int flag = 0;  /* 辅助调整输出格式用 */ 
200 
201     if (!P) {printf("0 0\n"); return;} 202 
203     while ( P ) 204  { 205         if (!flag) flag = 1; 206         else    printf(" "); 207         printf("%d %d", P->coef, P->expon); 208         P = P->link; 209  } 210     printf("\n"); 211 } 212  
213 int main() 214 { 215  Polynomial P1, P2, PP, PS; 216     
217     P1 = ReadPoly(); 218     P2 = ReadPoly(); 219     PP = Mult( P1, P2 ); 220  PrintPoly( PP ); 221     PS = Add( P1, P2 ); 222  PrintPoly( PS ); 223     
224     return 0; 225 }

02-线性结构3 Reversing Linked List

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤) which is the total number of nodes, and a positive K (≤) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

00100 6 4

00000 4 99999

00100 1 12309

68237 6 -1

33218 3 00000

99999 5 68237

12309 2 33218

Sample Output:

00000 4 33218

33218 3 12309

12309 2 00100

00100 1 99999

99999 5 68237

68237 6 -1

 1 /* 
 2 1.结点的地址用数组的下标表示,经过数组下标能够索引到结点的Data值,结点的Next值;  3 2.从首结点的地址FirstAdd开始,经过索引Next把结点的地址串起来;  4 3.用一个顺序表List连续存储结点的地址,结点的关系是连续的下标表示,由于表元素值就是结点地址;  5 4.List逆序就是地址逆序,经过逆序后的地址(结点下标)能够索引到结点,List的下一个元素值,  6 就是结点的下一个结点地址;  7  */
 8 #include<stdio.h>
 9 #define MaxSize 100005
10 int main() 11 { 12     int Data[MaxSize]; 13     int Next[MaxSize]; 14     int list[MaxSize]; 15     int FirstAdd,N,K; 16     scanf("%d %d %d",&FirstAdd,&N,&K); 17     for(int i=0;i<N;i++){ 18         int tmpAdd,tmpData,tmpNext; 19         scanf("%d %d %d",&tmpAdd,&tmpData,&tmpNext); 20         Data[tmpAdd] = tmpData; 21         Next[tmpAdd] = tmpNext; 22  } 23     int sum=0;   // 累计有效结点数 
24     while(FirstAdd!=-1){   // 当尾结点为 -1 时结束 
25         list[sum++] = FirstAdd;   // 记录全部Address
26         FirstAdd = Next[FirstAdd];  // 找下一个结点 
27  } 28     for(int i=0;i<sum-sum%K;i+=K){  // 每 K 个结点一个区间 
29         for(int j=0;j<K/2;j++){  // 反转链表
30             int t = list[i+j]; 31             list[i+j] = list[i+K-j-1]; 32             list[i+K-j-1] = t; 33  } 34  } 35     for(int i=0;i<sum-1;i++) 36         printf("%05d %d %05d\n",list[i],Data[list[i]],list[i+1]); 37     printf("%05d %d -1\n",list[sum-1],Data[list[sum-1]]); 38     return 0; 39 }

02-线性结构4 Pop Sequence

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

Input Specification:

Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.

Output Specification:

For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.

Sample Input:

5 7 5

1 2 3 4 5 6 7

3 2 1 7 5 6 4

7 6 5 4 3 2 1

5 6 4 3 7 2 1

1 7 6 5 4 3 2

Sample Output:

YES

NO

NO

YES

NO

 1 #include <stdio.h>
 2 #define N 1000
 3 int main()  4 {  5     int m,n,k;//m栈的最大容量, n压栈元素个数, k行测试数列
 6     scanf("%d%d%d", &m, &n, &k);  7     for(int i=0; i<k; i++)//k行测试数列
 8  {  9         int stack[N]; //
10         int top = -1; 11         int arr[N];   //数列数组
12         for(int j=0; j<n; j++)//输入一个数列
13             scanf("%d", &arr[j]); 14         int count = 0; //相同个数(做为arr下标)
15         for(int j=1; j<=n; j++)//从数字1开始压栈
16  { 17             stack[++top] = j;//压栈
18             if(top + 1 > m)//第一个栈元素下标为0
19                 break; 20             while(top != -1 && stack[top]==arr[count]) 21  { 22                 top--; 23                 count++; 24  } 25  } 26         if(count == n) 27             printf("YES\n"); 28         else
29             printf("NO\n"); 30  } 31     return 0; 32 }

03-1 树的同构

给定两棵树T1T2。若是T1能够经过若干次左右孩子互换就变成T2,则咱们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,由于咱们把其中一棵树的结点ABG的左右孩子互换后,就获得另一棵树。而图2就不是同构的。

 

1

 

 

2

现给定两棵树,请你判断它们是不是同构的。

输入格式:

输入给出2棵二叉树树的信息。对于每棵树,首先在一行中给出一个非负整数N (10),即该树的结点数(此时假设结点从0N−1编号);随后N行,第i行对应编号第i个结点,给出该结点中存储的1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。若是孩子结点为空,则在相应位置上给出“-”。给出的数据间用一个空格分隔。注意:题目保证每一个结点中存储的字母是不一样的。

输出格式:

若是两棵树是同构的,输出“Yes”,不然输出“No”。

输入样例1(对应图1):

8

A 1 2

B 3 4

C 5 -

D - -

E 6 -

G 7 -

F - -

H - -

8

G - 4

B 7 6

F - -

A 5 1

H - -

C 0 -

D - -

E 2 -  

输出样例1:

Yes

输入样例2(对应图2):

8

B 5 7

F - -

A 0 3

C 6 -

H - -

D - -

G 4 -

E 1 -

8

D 6 -

B 5 -

E - -

H - -

C 0 2

G - 3

F - -

A 1 4  

输出样例2:

No

 1 #include <stdio.h>
 2 #include <malloc.h>
 3 #define null -1
 4 /* 定义树结点 */
 5 struct TreeNode{  6     char data;  // 存值 
 7     int left;   // 左子树的下标 
 8     int right;  // 右子树的下标 
 9 }T1[10],T2[10]; 10 
11 /* 构造树并返回根结点 */
12 int create(struct TreeNode T[]) 13 { 14     int n; 15     int root = 0; 16     char left, right; 17     /* 输入结点数 */
18     scanf("%d", &n); 19     /* 空树 */
20     if(!n) 21         return null; 22     for(int i=0;i<n;i++) 23  { 24         root +=i;  /* 累加i*/  
25         /* 输入数据 */
26         scanf(" %c %c %c", &T[i].data, &left, &right); 27         /* 1.left */
28         if(left=='-') 29             T[i].left = null; 30         else{ 31             T[i].left = left-'0'; 32             root -= T[i].left; //
33  } 34         /* 2.right */
35         if(right=='-') 36             T[i].right = null; 37         else{ 38             T[i].right = right-'0'; 39             root -= T[i].right;//
40  } 41  } 42     return root; 43 } 44 /* 判断是否同构 */
45 int judge(int R1,int R2) 46 { 47     /* 1.两棵树都为空 */
48     if(R1 == null && R2 == null) 49         return 1; 50     /* 2.一个为空,一个不为空 */
51     if(R1 == null && R2 != null || R1 != null && R2 == null) 52         return 0; 53     /* 3.两颗树的值不一样 */
54     if(T1[R1].data != T2[R2].data) 55         return 0; 56     /* 4.左儿子为空*/
57     if(T1[R1].left == null && T2[R2].left == null) 58         return judge(T1[R1].right,T2[R2].right); 59     /* 5.左儿子不为空且值相等*/
60     if((T1[R1].left != null && T2[R2].left != null ) 61                             &&(T1[T1[R1].left].data == T2[T2[R2].left].data)) 62         return judge(T1[R1].left,T2[R2].left) 63                             &&judge(T1[R1].right,T2[R2].right); 64     /* 6.左儿子不为空且值不等 或者 某一个树的左儿子为空*/
65     else   
66         return judge(T1[R1].right,T2[R2].left) 67             && judge(T1[R1].left,T2[R2].right); 68 } 69 int main() 70 { 71     int R1,R2; 72     R1 = create(T1); 73     R2 = create(T2); 74     if(judge(R1,R2)) 75         printf("Yes"); 76     else
77         printf("No"); 78     return 0; 79 }

03-树2 List Leaves

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

8

1 -

- -

0 -

2 7

- -

- -

5 -

4 6

Sample Output:

4 1 5

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <malloc.h>
 4 #include <stdbool.h>
 5 
 6 /* 定义树结构(顺序存储) */
 7 #define null -1 //-1 表示空
 8 struct TreeNode{  9     int data;   // 数据 0~N-1
 10     int left;   // 左儿子下标
 11     int right;  // 右儿子下标
 12 }T[10]; //最大10个结点
 13 
 14 /* 顺序循环队列(队头指针在第一个元素前)*/
 15 #define MAXSIZE  10 //最大队列长度 N 
 16 typedef int Position; //队列的头\尾指针类型
 17 typedef struct TreeNode ElementType; //队列元素类型 
 18 typedef struct QNode *Queue;  19 struct QNode {  20     ElementType *Data;     /* 存储元素的数组 */
 21     Position Front, Rear;  /* 队列的头、尾指针 */
 22     int MaxSize;           /* 队列最大容量 */
 23 };  24 
 25  /* 建队列 */
 26 Queue CreateQueue( int MaxSize )//返回队列指针
 27 {  28     Queue Q = (Queue)malloc(sizeof(struct QNode));  29     Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));  30     Q->Front = Q->Rear = 0;  31     Q->MaxSize = MaxSize;  32     return Q;  33 }  34 
 35 /* 队满 */
 36 bool IsFull( Queue Q )  37 {  38     return ((Q->Rear+1)%Q->MaxSize == Q->Front);  39 }  40 
 41 /* 队空 */
 42 bool IsEmpty( Queue Q )  43 {  44     return (Q->Front == Q->Rear);  45 }  46 
 47 /* 入队 */
 48 bool AddQ( Queue Q, ElementType X )  49 {  50     if ( IsFull(Q) ) {  51         return false;  52  }  53     else {  54         Q->Rear = (Q->Rear+1)%Q->MaxSize;  55         Q->Data[Q->Rear] = X;  56         return true;  57  }  58 }  59 
 60 /* 出队 */
 61 ElementType* DeleteQ( Queue Q )  62 {  63     if ( IsEmpty(Q) )  64         return NULL;  65     Q->Front =(Q->Front+1)%Q->MaxSize;  66     return  &Q->Data[Q->Front];  67 }  68 
 69 // 树结点输入
 70 int create()  71 {  72     int n;  73     int root = 0;  74     char left, right;  75     
 76     scanf("%d", &n);  77     if(!n) //结点数为0, 返回空(-1)
 78         return null;  79     
 80     for(int i=0; i<n; i++)  81  {  82         root += i;//累加
 83         T[i].data = i; //数据0~N-1
 84         
 85         scanf(" %c %c", &left, &right);  86         
 87         if(left=='-')//左儿子下标
 88             T[i].left = null;  89         else{  90             T[i].left = left-'0';  91             root -= T[i].left;//
 92  }  93         
 94         if(right=='-')//右儿子下标
 95             T[i].right = null;  96         else{  97             T[i].right = right-'0';  98             root -= T[i].right;//
 99  } 100  } 101     return root; 102 } 103 
104 // 层序遍历(从上到下从左到右) 
105 void LevelorderTraversal(int root) 106 { 107     if(root == null){ 108         printf("-");// 树为空,输出"-"
109         return; 110  } 111     
112     Queue q = CreateQueue(MAXSIZE);//建队列(指针)
113     bool flag = false; //控制空格输出
114     AddQ(q, T[root]); //树根入队
115     
116     while(!IsEmpty(q)) 117  { 118         ElementType* t = DeleteQ(q);// 出队, 返回队首元素
119         
120         if(t->left == null && t->right == null) 121         {  //若是为叶子结点就输出 
122             if(flag) 123                 printf(" "); 124             else
125                 flag = true; 126             printf("%d", t->data); 127  } 128         
129         if(t->left != null)  // 有左儿子入队
130             AddQ(q, T[t->left]); 131         if(t->right != null)  // 有右儿子入队
132             AddQ(q, T[t->right]); 133  } 134 } 135  
136 int main() 137 { 138     int root = create(); 139  LevelorderTraversal(root); 140     return 0; 141 }

03-树3 Tree Traversals Again

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

  Figure 1

Sample Input:

6

Push 1

Push 2

Push 3

Pop

Pop

Push 4

Pop

Pop

Push 5

Push 6

Pop

Pop

Sample Output:

3 4 2 6 5 1

 1 #include <stdio.h>
 2 #include <stdlib.h> //atoi
 3 #include <string.h> //strcmp
 4 
 5 #define N 31
 6 typedef int ElementType;  7 typedef struct TreeNode *Tree;//树类型
 8 struct TreeNode{  9     ElementType data;  // 数字 1 ~ N
10     Tree left;         // 左子树 
11     Tree right;        // 右子树 
12 }; 13 
14 typedef Tree Stack;//树栈类型 15 
16 //先序遍历建树 
17 Tree PreorderTraversal() 18 { 19     Tree T = (Tree)malloc(sizeof(struct TreeNode)); 20     T->left = NULL; 21     T->right = NULL; //树根
22     Tree t = T; 23     
24     Stack s[N];    //树栈
25     int top = -1; 26     
27     int n; 28     scanf("%d\n",&n); 29     
30     char str[N];   //字符串 
31  gets(str); 32     
33     t->data = atoi(&str[5]); // 根节点data 
34     s[++top] = t;            //根结点入栈 
35 
36     for(int i=1; i<2*n; i++) //2N lines
37  { 38         gets(str);              //逐行读取
39         if(!strcmp(str,"Pop")){ //Pop
40             t = s[top];         //出栈指针
41             top--; 42         }else{                  // Push 
43             Tree tmp  = (Tree)malloc(sizeof(struct TreeNode)); 44             tmp->left = NULL; 45             tmp->right = NULL; 46             tmp->data = atoi(&str[5]); //树结点data 
47             s[++top] = tmp;     //新结点入栈
48             
49             if(!t->left){       // 左插
50                 t->left = tmp; 51                 t = t->left; 52             }else if(!t->right){ //右插
53                 t->right = tmp; 54                 t = t->right; 55  } 56  } 57  } 58     return T; 59 } 60 
61 // 后序递归遍历
62 void PostorderTraversal(Tree T, int *flag) 63 { 64     if(T){ 65         PostorderTraversal(T->left,flag); 66         PostorderTraversal(T->right,flag); 67         if(!(*flag)) 68             *flag = 1; 69         else
70             printf(" "); 71         printf("%d", T->data); 72  } 73 } 74 
75 int main() 76 { 77     Tree T = PreorderTraversal(); //先序建树
78     int flag = 0; 79     PostorderTraversal(T,&flag); //后序输出
80     return 0; 81 }

04-树7 二叉搜索树的操做集

本题要求实现给定二叉搜索树的5种经常使用操做。

函数接口定义:

BinTree Insert( BinTree BST, ElementType X ); BinTree Delete( BinTree BST, ElementType X ); Position Find( BinTree BST, ElementType X ); Position FindMin( BinTree BST ); Position FindMax( BinTree BST );

其中BinTree结构定义以下:

typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; };

函数Insert将X插入二叉搜索树BST并返回结果树的根结点指针;

函数Delete将X从二叉搜索树BST中删除,并返回结果树的根结点指针;若是X不在树中,则打印一行Not Found并返回原树的根结点指针;

函数Find在二叉搜索树BST中找到X,返回该结点的指针;若是找不到则返回空指针;

函数FindMin返回二叉搜索树BST中最小元结点的指针;

函数FindMax返回二叉搜索树BST中最大元结点的指针。

#include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; }; void PreorderTraversal( BinTree BT ); /* 先序遍历,由裁判实现,细节不表 */
void InorderTraversal( BinTree BT );  /* 中序遍历,由裁判实现,细节不表 */ BinTree Insert( BinTree BST, ElementType X ); BinTree Delete( BinTree BST, ElementType X ); Position Find( BinTree BST, ElementType X ); Position FindMin( BinTree BST ); Position FindMax( BinTree BST ); int main() { BinTree BST, MinP, MaxP, Tmp; ElementType X; int N, i; BST = NULL; scanf("%d", &N); for ( i=0; i<N; i++ ) { scanf("%d", &X); BST = Insert(BST, X); } printf("Preorder:"); PreorderTraversal(BST); printf("\n"); MinP = FindMin(BST); MaxP = FindMax(BST); scanf("%d", &N); for( i=0; i<N; i++ ) { scanf("%d", &X); Tmp = Find(BST, X); if (Tmp == NULL) printf("%d is not found\n", X); else { printf("%d is found\n", Tmp->Data); if (Tmp==MinP) printf("%d is the smallest key\n", Tmp->Data); if (Tmp==MaxP) printf("%d is the largest key\n", Tmp->Data); } } scanf("%d", &N); for( i=0; i<N; i++ ) { scanf("%d", &X); BST = Delete(BST, X); } printf("Inorder:"); InorderTraversal(BST); printf("\n"); return 0; } /* 你的代码将被嵌在这里 */

输入样例:

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

输出样例:

Preorder: 5 2 1 0 4 8 6 7 10 9
6 is found 3 is not found 10 is found 10 is the largest key 0 is found 0 is the smallest key 5 is found Not Found Inorder: 1 2 4 6 8 9
 1 // 插入 
 2 BinTree Insert( BinTree BST, ElementType X ){  3     if(!BST){  // 若是为空,建立新结点 
 4         BST = (BinTree)malloc(sizeof(struct TNode));  5         BST->Data = X;  6         BST->Left = NULL;  7         BST->Right = NULL;  8     }else{  9         if(X < BST->Data) 10             BST->Left = Insert(BST->Left,X); 11         else if(BST->Data < X) 12             BST->Right = Insert(BST->Right,X); 13  } 14     return BST; 15 } 16 
17 // 删除
18 BinTree Delete( BinTree BST, ElementType X ){ 19  BinTree tmp; 20     if(!BST){ 21         printf("Not Found\n"); 22         return BST; 23     }else{ 24         if(X < BST->Data) 25             BST->Left = Delete(BST->Left,X); 26         else if(BST->Data < X) 27             BST->Right = Delete(BST->Right,X); 28         else{  // 找到要删除结点 
29             if(BST->Left && BST->Right){  // 若是该结点有左右儿子 
30                 tmp = FindMin(BST->Right); 31                 BST->Data = tmp->Data; 32                 BST->Right = Delete(BST->Right,tmp->Data); 33             }else{ 34                 tmp = BST; 35                 if(BST->Left && !BST->Right) 36                     BST = BST->Left; 37                 else if(!BST->Left && BST->Right) 38                     BST = BST->Right; 39                 else
40                     BST = NULL; 41                 free(tmp); 42  } 43  } 44  } 45     return BST; 46 } 47 
48 // 寻找值最小结点 
49 Position FindMin( BinTree BST ){ 50     if(BST) 51         while(BST->Left) 52             BST = BST->Left; 53     return BST; 54 } 55 
56 // 寻找值最大结点
57 Position FindMax( BinTree BST ){ 58     if(BST) 59         while(BST->Right) 60             BST = BST->Right; 61     return BST; 62 } 63 
64 // 查找
65 Position Find( BinTree BST, ElementType X ){ 66     if(!BST){ 67         return NULL; 68     }else if(X < BST->Data) 69         return Find(BST->Left,X); 70     else if(BST->Data < X) 71         return Find(BST->Right,X); 72     else
73         return BST; 74 }

04-树4 是否同一棵二叉搜索树 

给定一个插入序列就能够惟一肯定一棵二叉搜索树。然而,一棵给定的二叉搜索树却能够由多种不一样的插入序列获得。例如分别按照序列{2, 1, 3}和{2, 3, 1}插入初始为空的二叉搜索树,都获得同样的结果。因而对于输入的各类插入序列,你须要判断它们是否能生成同样的二叉搜索树。 

输入格式:

输入包含若干组测试数据。每组数据的第1行给出两个正整数N (≤10)和L,分别是每一个序列插入元素的个数和须要检查的序列个数。第2行给出N个以空格分隔的正整数,做为初始插入序列。最后L行,每行给出N个插入的元素,属于L个须要检查的序列。

简单起见,咱们保证每一个插入序列都是1到N的一个排列。当读到N为0时,标志输入结束,这组数据不要处理。

输出格式:

对每一组须要检查的序列,若是其生成的二叉搜索树跟对应的初始序列生成的同样,输出“Yes”,不然输出“No”。

输入样例:

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

输出样例:

Yes No No
 1 #include <stdio.h>
 2 #include <malloc.h>
 3 /* 树结点定义 */
 4 typedef struct TreeNode *Tree;  5 struct TreeNode {  6     int v;  7  Tree Left, Right;  8     int flag; /* 判别结点是否访问过的标记 */
 9 };  10 
 11 /* 函数声明  12  1.建立一个树结点  13  2.插入一个树结点  14  3.建立一棵树  15  4.检查树结点是否访问过  16  5.判断是否同一棵树  17  6.清除树中各结点的flag标记  18  7.释放树的空间  19 */
 20 Tree NewNode( int V );  21 Tree Insert( Tree T, int V );  22 Tree MakeTree( int N );  23 int check ( Tree T, int V );  24 int Judge( Tree T, int N );  25 void ResetT ( Tree T );  26 void FreeTree ( Tree T );  27 
 28 /* 主程序 */
 29 int main()  30 {  31     int N, L, i;  32     Tree T; /* 建立一个树的空结点 */
 33     scanf("%d", &N);  34     while (N)  35  {  36         scanf("%d", &L);  37         T = MakeTree(N); /* 建立一棵N个结点的树 */
 38         for (i=0; i<L; i++)  39         {   /* 判断是否同一棵树 */
 40             if (Judge(T, N)) printf("Yes\n");  41             else printf("No\n");  42             ResetT(T); /*清除T中的标记flag*/
 43  }  44         FreeTree(T); /* 释放上面的树空间 */
 45         scanf("%d", &N);  46  }  47     return 0;  48 }  49 /* 建立一个树结点 */
 50 Tree NewNode( int V )  51 {  52     Tree T = (Tree)malloc(sizeof(struct TreeNode));  53     T->v = V;  54     T->Left = T->Right = NULL;  55     T->flag = 0;  56     return T;  57 }  58 /* 插入一个树结点 */
 59 Tree Insert( Tree T, int V )  60 {  61     if ( !T ) T = NewNode(V);  62     else 
 63  {  64         if ( V > T->v )  65             T->Right = Insert( T->Right, V );  66         else
 67             T->Left = Insert( T->Left, V );  68  }  69     return T;  70 }  71 /* 建立一棵N个结点的树 */
 72 Tree MakeTree( int N )  73 {  74  Tree T;  75     int i, V;  76     scanf("%d", &V);  77     T = NewNode(V); /*  */
 78     for (i=1; i<N; i++)  79  {  80         scanf("%d", &V);  81         T = Insert(T, V); /*  */
 82  }  83     return T;  84 }  85 /* 判断树的结点是否访问过 */
 86 int check ( Tree T, int V )  87 {  88     if ( T->flag )  89  {  90         if ( V<T->v ) return check(T->Left, V);  91         else if ( V>T->v ) return check(T->Right, V);  92         else return 0;  93  }  94     else 
 95  {  96         if ( V==T->v )  97  {  98             T->flag = 1;  99             return 1; 100  } 101         else return 0; 102  } 103 } 104 /* 判断是否同一棵树 */
105 int Judge( Tree T, int N ) 106 { 107     int i, V, flag = 0; 108     /* flag, 0表明目前还一致, 1表明已经不一致*/
109     scanf("%d", &V); 110     if ( V!=T->v ) flag = 1; 111     else T->flag = 1; 112     for (i=1; i<N; i++) 113  { 114         scanf("%d", &V);/* 读取结点的V */
115         if ( (!flag) && (!check(T, V)) ) flag = 1; 116  } 117     return !flag; /* 1表明已经不一致 */
118 } 119 /* 清除T中各结点的flag标记 */
120 void ResetT ( Tree T ) 121 { 122     if (T->Left) ResetT(T->Left); 123     if (T->Right) ResetT(T->Right); 124     T->flag = 0; 125 } 126 /* 释放T的空间 */
127 void FreeTree ( Tree T ) 128 { 129     if (T->Left) FreeTree(T->Left); 130     if (T->Right) FreeTree(T->Right); 131     free(T); 132 }

04-树5 Root of AVL Tree

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

 

 

Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

Sample Input 1:

5
88 70 61 96 120

Sample Output 1:

70

Sample Input 2:

7
88 70 61 96 120 90 65

Sample Output 2:

88
 1 #include <stdio.h>
 2 #include <malloc.h>
 3 
 4 typedef int ElementType;  5 typedef struct AVLNode *Position;  6 typedef Position AVLTree; /* AVL树类型 */
 7 struct AVLNode{  8     ElementType Data; /* 结点数据 */
 9     AVLTree Left;     /* 指向左子树 */
 10     AVLTree Right;    /* 指向右子树 */
 11     int Height;       /* 树高 */
 12 };  13 
 14 /* AVL树左右单旋\左右双旋\右左双旋\插入 */
 15 int GetHeight( AVLTree A ); /* 树高 */
 16 int Max ( int a, int b );   /* 结点数据大小 */
 17 AVLTree SingleLeftRotation ( AVLTree A );  18 AVLTree SingleRightRotation ( AVLTree A );  19 AVLTree DoubleLeftRightRotation ( AVLTree A );  20 AVLTree DoubleRightLeftRotation ( AVLTree A );  21 AVLTree Insert( AVLTree T, ElementType X );  22  
 23 /* 主程序 */
 24 int main()  25 {  26     AVLTree AVLT = NULL;  27     int N, i;  28  ElementType X;  29     scanf("%d", &N);  30     for ( i=0; i<N; i++ ) {  31         scanf("%d", &X);  32         AVLT = Insert(AVLT, X);  33  }  34     printf("%d\n", AVLT->Data);  35     return 0;  36 }  37 
 38 /* 树高 */
 39 int GetHeight(AVLTree A)  40 {  41     if(!A) return -1;  42     return A->Height;  43 }  44 
 45 /* 树数据大小 */
 46 int Max ( int a, int b )  47 {  48     return a > b ? a : b;  49 }  50 
 51 /* 左单旋 */
 52 AVLTree SingleLeftRotation ( AVLTree A )  53 { /* 注意:A必须有一个左子结点B */
 54   /* 将A与B作左单旋,更新A与B的高度,返回新的根结点B */     
 55  
 56     AVLTree B = A->Left;  57     A->Left = B->Right;  58     B->Right = A;  59     A->Height = Max( GetHeight(A->Left), GetHeight(A->Right) ) + 1;  60     B->Height = Max( GetHeight(B->Left), A->Height ) + 1;  61   
 62     return B;  63 }  64 
 65 /* 右单旋 */
 66 AVLTree SingleRightRotation ( AVLTree A )  67 { /* 注意:A必须有一个右子结点B */
 68   /* 将A与B作右单旋,更新A与B的高度,返回新的根结点B */     
 69  
 70     AVLTree B = A->Right;  71     A->Right = B->Left;  72     B->Left = A;  73     A->Height = Max( GetHeight(A->Left), GetHeight(A->Right) ) + 1;  74     B->Height = Max( GetHeight(B->Left), A->Height ) + 1;  75   
 76     return B;  77 }  78 
 79 /* 左右双旋 */
 80 AVLTree DoubleLeftRightRotation ( AVLTree A )  81 { /* 注意:A必须有一个左子结点B,且B必须有一个右子结点C */
 82   /* 将A、B与C作两次单旋,返回新的根结点C */
 83      
 84     /* 将B与C作右单旋,C被返回 */
 85     A->Left = SingleRightRotation(A->Left);  86     /* 将A与C作左单旋,C被返回 */
 87     return SingleLeftRotation(A);  88 }  89 
 90 /* 右左双旋 */
 91 AVLTree DoubleRightLeftRotation ( AVLTree A )  92 { /* 注意:A必须有一个右子结点B,且B必须有一个左子结点C */
 93   /* 将A、B与C作两次单旋,返回新的根结点C */
 94      
 95     /* 将B与C作右单旋,C被返回 */
 96     A->Right = SingleLeftRotation(A->Right);  97     /* 将A与C作右单旋,C被返回 */
 98     return SingleRightRotation(A);  99 } 100 
101 /* 插入 */
102 AVLTree Insert( AVLTree T, ElementType X ) 103 { /* 将X插入AVL树T中,而且返回调整后的AVL树 */
104     if ( !T ) { /* 若插入空树,则新建包含一个结点的树 */
105         T = (AVLTree)malloc(sizeof(struct AVLNode)); 106         T->Data = X; 107         T->Height = 0; 108         T->Left = T->Right = NULL; 109     } /* if (插入空树) 结束 */
110  
111     else if ( X < T->Data ) { 112         /* 插入T的左子树 */
113         T->Left = Insert( T->Left, X); 114         /* 若是须要左旋 */
115         if ( GetHeight(T->Left)-GetHeight(T->Right) == 2 ) 116             if ( X < T->Left->Data ) 117                T = SingleLeftRotation(T);      /* 左单旋 */
118             else 
119                T = DoubleLeftRightRotation(T); /* 左-右双旋 */
120     } /* else if (插入左子树) 结束 */
121      
122     else if ( X > T->Data ) { 123         /* 插入T的右子树 */
124         T->Right = Insert( T->Right, X ); 125         /* 若是须要右旋 */
126         if ( GetHeight(T->Left)-GetHeight(T->Right) == -2 ) 127             if ( X > T->Right->Data ) 128                T = SingleRightRotation(T);     /* 右单旋 */
129             else 
130                T = DoubleRightLeftRotation(T); /* 右-左双旋 */
131     } /* else if (插入右子树) 结束 */
132  
133     /* else X == T->Data,无须插入 */
134  
135     /* 别忘了更新树高 */
136     T->Height = Max( GetHeight(T->Left), GetHeight(T->Right) ) + 1; 137      
138     return T; 139 }

04-树6 Complete Binary Search Tree 

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

The left subtree of a node contains only nodes with keys less than the node's key.

The right subtree of a node contains only nodes with keys greater than or equal to the node's key.

Both the left and right subtrees must also be binary search trees.

A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input:

10

1 2 3 4 5 6 7 8 9 0

Sample Output:

6 3 8 1 5 7 9 0 2 4

 1 #include <stdio.h>
 2 #include <math.h>
 3 
 4 #define MaxSize 2001
 5 int value[MaxSize]; /* BST树 */
 6 int BST[MaxSize];   /* 彻底二叉树 */
 7 
 8 /* 计算 n 个结点的树其左树结点个数 */ 
 9 int getLeftTreeSize(int n) 10 { 11     int h = 0;   /* 0.保存该结点下满二叉树的层数 */ 
12     int tmp = n+1;    /* n+1, 结点为1的状况下,1+1除以2结果为1 */
13     while( tmp != 1 ) 14  { 15         tmp /= 2; /* 每层比上一层多2倍, 除以2就是一层 */
16         h++; 17  } 18     /* 1.最下面一排叶结点个数 */ 
19     int x = n - (pow(2,h)-1); 20     /* 2.左子树的叶结点个数最可能是 2^(h-1) 21  若是最下一排叶结点含有右树叶结点,即大于2^(h-1) 22  取左子树最大叶结点数2^(h-1) */
23     x = x<pow(2,h-1) ? x: pow(2,h-1); 24     /* 3.左子树的个数 */ 
25     int L = pow(2,h-1)-1 + x; 26     /* 
27  左满树 + 左叶子结点 == 左子树的结点数, 28  左满树 比 根满树 低一层 pow(2,h-1)-1 29  根满树pow(2,h)-1 30  根满树 + 最下面一排叶子结点数 == n 31     */
32     return L; 33 } 34 
35 /* 填充函数 */
36 void fill(int left,int right,int root) 37 { 38     int n = right - left + 1;  // 肯定范围内数值个数 
39      if(!n) 40          return; 41      int L = getLeftTreeSize(n);   // 找到"偏移量" 
42      BST[root] = value[left + L];  // 根结点的值 左边界值 + 偏移量 
43      int leftRoot = 2 * root + 1;   // 左儿子结点位置,因为从 0 开始 
44      int rightRoot = leftRoot + 1;  // 右儿子结点位置 
45      fill(left, left+L-1, leftRoot);    // 左子树递归 
46      fill(left+L+1, right, rightRoot);  // 右子树递归 
47 } 48 
49 void QuickSort(int *a, int n, int left, int right) 50 { 51     int i, j, t; 52         /*左指针left指向数组头 右指针right指向数组尾*/
53     if(left<right) 54  { 55         i = left, j = right+1;/*左右指针*/
56         while(i<j) 57  { 58             while(i+1<n && a[++i]<a[left]);/*左指针右移 指向大于基数的数据中止*/
59             while(j-1>-1 && a[--j]>a[left]);/*右指针左移 指向小于基数的数据中止*/
60             if(i<j)/*知足左指针小于右指针的条件 两指针指向数据交换*/
61                 t = a[i], a[i] = a[j], a[j] = t; 62  } 63         t = a[left], a[left] = a[j], a[j] = t;/*右指针指向数据与基数交换*/
64         QuickSort(a, n, left, j-1);/*左边数据递归*/
65         QuickSort(a, n, j+1, right);/*右边数据递归*/
66  } 67 } 68 
69 int main() 70 { 71     int n; 72     scanf("%d", &n); 73     for(int i=0;i<n;i++) 74         scanf("%d", &value[i]); 75     /* BST树左小右大的属性 */
76     QuickSort( value, n, 0, n-1 ); /* 从小到大排序 */
77     fill( 0, n-1, 0 ); /* 彻底二叉树填充,下标从0开始 */
78     for(int i=0;i<n;i++) 79  { 80         if(i) 81             printf(" "); 82         printf("%d", BST[i]); 83  } 84     return 0; 85 }

05-树7 堆中的路径

将一系列给定数字插入一个初始为空的小顶堆H[]。随后对任意给定的下标i,打印从H[i]到根结点的路径。

输入格式:

每组测试第1行包含2个正整数N和M(≤1000),分别是插入元素的个数、以及须要打印的路径条数。下一行给出区间[-10000, 10000]内的N个要被插入一个初始为空的小顶堆的整数。最后一行给出M个下标。

输出格式:

对输入中给出的每一个下标i,在一行中输出从H[i]到根结点的路径上的数据。数字间以1个空格分隔,行末不得有多余空格。

输入样例:

5 3

46 23 26 24 10

5 4 3

输出样例:

24 23 10

46 23 10

26 10

 1 #include <stdio.h>
 2 
 3 /* 1.定义堆H */
 4 #define MAXN 1001
 5 #define MINH -10001
 6 int H[MAXN], size;  7 
 8 /* 2.堆的初始化 */
 9 void Create () 10 { 11     size = 0; 12     H[0] = MINH; 13 } 14 
15 /* 3.堆插入 */
16 void Insert ( int X ) 17 { 18     int i; 19     for (i=++size; H[i/2] > X; i/=2) 20         H[i] = H[i/2]; 21     H[i] = X; 22 } 23 
24 int main() 25 { 26     int n, m, x, i, j; 27     scanf("%d%d", &n, &m); 28  Create(); 29     for (i=0; i<n; i++) { 30         scanf("%d", &x); 31  Insert(x); 32  } 33         
34     for (i=0; i<m; i++) 35  { 36         scanf("%d", &j); 37         printf("%d", H[j]); 38         while (j>1) { 39             j /= 2; 40             printf(" %d", H[j]); 41  } 42         printf("\n"); 43  } 44     return 0; 45 }

05-树8 File Transfer

We have a network of computers and a list of bi-directional connections. Each of these connections allows a file transfer from one computer to another. Is it possible to send a file from any computer on the network to any other?

Input Specification:

Each input file contains one test case. For each test case, the first line contains N (2≤N≤10

​4), the total number of computers in a network. Each computer in the network is then represented by a positive integer between 1 and N. Then in the following lines, the input is given in the format:

I c1 c2 

where I stands for inputting a connection between c1 and c2; or

C c1 c2   

where C stands for checking if it is possible to transfer files between c1 and c2; or

S

where S stands for stopping this case.

Output Specification:

For each C case, print in one line the word "yes" or "no" if it is possible or impossible to transfer files between c1 and c2, respectively. At the end of each case, print in one line "The network is connected." if there is a path between any pair of computers; or "There are k components." where k is the number of connected components in this network.

Sample Input 1:

5

C 3 2

I 3 2

C 1 5

I 4 5

I 2 4

C 3 5

S

Sample Output 1:

no

no

yes

There are 2 components.

Sample Input 2:

5

C 3 2

I 3 2

C 1 5

I 4 5

I 2 4

C 3 5

I 1 3

C 1 5

S

Sample Output 2:

no

no

yes

yes

The network is connected.

 1 #include <stdio.h>
 2  
 3 /* 集合的简化 */
 4 #define MaxSize 10001 
 5 typedef int ElementType; /*默认元素能够用非负整数表示*/
 6 typedef int SetName; /*默认用根结点的下标做为集合名称*/
 7 typedef ElementType SetType[MaxSize];/* 定义集合类型 */
 8 
 9 /* Initialization */
10 void Initialization( SetType S , int n ) 11 { 12     int i; 13     for ( i=0; i<n; i++ ) S[i] = -1; 14 } 15 
16 /* find */
17 SetName Find( SetType S, ElementType X ) 18 { 19     if ( S[X] < 0 ) /* 找到集合的根 */
20         return X; 21     else    
22         return S[X] = Find( S, S[X] ); 23 } 24 
25 /* union */
26 void Union( SetType S, SetName Root1, SetName Root2 ) 27 {     /* 按规模 比元素个数,少的贴多的 */
28     if ( S[Root2]<S[Root1] ){ //负数,小即多
29         S[Root2] += S[Root1]; 30         S[Root1] = Root2; 31  } 32     else { 33         S[Root1] += S[Root2]; 34         S[Root2] = Root1; 35  } 36 } 37 
38 /* input */
39 void Input_connection( SetType S ) 40 { 41  ElementType u, v; 42  SetName Root1, Root2; 43     scanf("%d %d\n", &u, &v); 44     Root1 = Find(S, u-1); 45     Root2 = Find(S, v-1); 46     if ( Root1 != Root2 ) 47  Union( S, Root1, Root2 ); 48 } 49 
50 /* check connection */
51 void Check_connection( SetType S ) 52 { 53  ElementType u, v; 54  SetName Root1, Root2; 55     scanf("%d %d\n", &u, &v); 56     Root1 = Find(S, u-1); 57     Root2 = Find(S, v-1); 58     if ( Root1 == Root2 ) 59         printf("yes\n"); 60     else printf("no\n"); 61 } 62 
63 /* check network */
64 void Check_network( SetType S, int n ) 65 { 66     int i, counter = 0; 67     for (i=0; i<n; i++) { 68         if ( S[i] < 0 ) counter++; 69  } 70     if ( counter == 1 ) 71         printf("The network is connected.\n"); 72     else
73         printf("There are %d components.\n", counter); 74 } 75 
76 /* 测试 */
77 int main() 78 { 79  SetType S; 80     int n; 81     char in; 82     scanf("%d\n", &n); 83  Initialization( S, n ); 84     do { 85         scanf("%c", &in); 86         switch (in) { 87             case 'I': Input_connection( S ); break; 88             case 'C': Check_connection( S ); break; 89             case 'S': Check_network( S, n ); break; 90  } 91     } while ( in != 'S'); 92     return 0; 93 }

05-树9 Huffman Codes

In 1953, David A. Huffman published his paper "A Method for the Construction of Minimum-Redundancy Codes", and hence printed his name in the history of computer science. As a professor who gives the final exam problem on Huffman codes, I am encountering a big problem: the Huffman codes are NOT unique. For example, given a string "aaaxuaxz", we can observe that the frequencies of the characters 'a', 'x', 'u' and 'z' are 4, 2, 1 and 1, respectively. We may either encode the symbols as {'a'=0, 'x'=10, 'u'=110, 'z'=111}, or in another way as {'a'=1, 'x'=01, 'u'=001, 'z'=000}, both compress the string into 14 bits. Another set of code can be given as {'a'=0, 'x'=11, 'u'=100, 'z'=101}, but {'a'=0, 'x'=01, 'u'=011, 'z'=001} is NOT correct since "aaaxuaxz" and "aazuaxax" can both be decoded from the code 00001011001001. The students are submitting all kinds of codes, and I need a computer program to help me determine which ones are correct and which ones are not.

Input Specification:

Each input file contains one test case. For each case, the first line gives an integer N (2≤N≤63), then followed by a line that contains all the N distinct characters and their frequencies in the following format:

c[1] f[1] c[2] f[2] ... c[N] f[N]

where c[i] is a character chosen from {'0' - '9', 'a' - 'z', 'A' - 'Z', '_'}, and f[i] is the frequency of c[i] and is an integer no more than 1000. The next line gives a positive integer M (≤1000), then followed by M student submissions. Each student submission consists of N lines, each in the format:

c[i] code[i]

where c[i] is the i-th character and code[i] is an non-empty string of no more than 63 '0's and '1's.

Output Specification:

For each test case, print in each line either "Yes" if the student's submission is correct, or "No" if not.

Note: The optimal solution is not necessarily generated by Huffman algorithm. Any prefix code with code length being optimal is considered correct.

Sample Input:

7 A 1 B 1 C 1 D 3 E 3 F 6 G 6
4 A 00000 B 00001 C 0001 D 001 E 01 F 10 G 11 A 01010 B 01011 C 0100 D 011 E 10 F 11 G 00 A 000 B 001 C 010 D 011 E 100 F 101 G 110 A 00000 B 00001 C 0001 D 001 E 00 F 10 G 11

Sample Output:

Yes Yes No No
 1 /* 
 2  建一个最小堆, 堆插入树结点, 造成树结点森林;  3  每次从堆中取2个最小树结点, 建中间树结点并插入堆;  4  最后堆中森林造成一棵Huffman树并计算WPL;  5  判断前缀码\结点数\WPL, 肯定编码是否正确;  6 */
 7 
 8 #include <stdio.h>
 9 #include <stdlib.h>
 10 #include <string.h>
 11 
 12 /* 二叉树结点 */
 13 typedef struct TreeNode* Tree;  14 struct TreeNode {  15     int Weight;  16  Tree Left, Right;  17 };  18 
 19 /* 堆(优先队列) */
 20 #define MAXSIZE 256 
 21 typedef struct HeapNode* Heap;  22 struct HeapNode {  23     struct TreeNode Data[MAXSIZE];/* 彻底二叉树顺序存储 */
 24     int Size;  25 };  26  
 27 Tree NewTreeNode();/* 建树结点 */
 28 Heap CreatHeap(); /* 建空堆 */
 29 void Insert(Heap H, struct TreeNode T);/* 堆插入 */
 30 Tree Delete(Heap H);/* 堆删除 */
 31 Tree Huffman(Heap H); /* 建Huffman树 */
 32 int WPL(Tree T, int Depth);/* 整棵树的WPL */
 33 
 34 int Judge(int codelen, int Weight[], int N) ; /* 判断是否正确的Huffman编码 */
 35 
 36 int main()  37 {  38     int N, Weight[MAXSIZE] = {0};  39     char ch;  40    
 41     Heap H = CreatHeap(); /* 建空堆 */
 42     Tree T = NewTreeNode();  /* 建临时树结点 */
 43     
 44     scanf("%d", &N);  /* 树结点个数 */
 45     for(int i = 0; i < N; i++)  46  {  47         scanf(" %c", &ch);  48         scanf("%d", &Weight[ch]);  49         T->Weight = Weight[ch];  50         H->Data[H->Size].Left = H->Data[H->Size].Right = NULL;  51         Insert(H, *T); /* 复制建立的树结点(传参), 插入堆, 造成树森林 */
 52  }  53     
 54     free(T); /* 释放临时结点 */
 55     
 56     T = Huffman(H);   /* 建Huffman树 */
 57     
 58     int codelen = WPL(T, 0); /* 求Huffman树的WPL */    
 59     int M;  /* M棵树 */
 60     scanf("%d", &M);  61     
 62     while(M--)  63     {    /* 一次判断一棵树 */
 64         if(Judge(codelen, Weight, N)) printf("Yes\n");  65         else printf("No\n");  66  }  67     
 68     return 0;  69 }  70 
 71  /* 建树结点 */
 72 Tree NewTreeNode() {  73  Tree T;  74     T = (Tree)malloc(sizeof(struct TreeNode));  75     T->Weight = 0;  76     T->Left = T->Right = NULL;  77     return T;  78 }  79 
 80  /* 建空堆 */
 81 Heap CreatHeap() {  82  Heap H;  83     H = (Heap)malloc(sizeof(struct HeapNode));  84     H->Size = 0;            /* 空堆 */
 85     H->Data[0].Weight = -1; /* 哨兵 */
 86     return H;  87 }  88  
 89  /* 堆插入 */
 90 void Insert(Heap H, struct TreeNode T) {  91     int i = ++H->Size;  /* ++堆, 从堆的最后开始寻找插入结点位置 */
 92     for( ; T.Weight < H->Data[i/2].Weight; i /= 2)  93         H->Data[i] = H->Data[i/2]; /* 父结点下滤 */
 94     H->Data[i] = T; /* 插入结点 */
 95 }  96 
 97  /* 堆删除 */
 98 Tree Delete(Heap H)  99 {    /* 提取堆最后一个树结点, 从堆的第一个结点开始比较,上滤, 堆-- */
100     int parent, child; 101     struct TreeNode Temp = H->Data[H->Size--]; /* 提取堆最后一个树结点 */
102     Tree T = NewTreeNode(); /* 建立树结点 */
103     *T = H->Data[1];        /* 从堆中提取第一个树结点 */
104     for(parent = 1; 2*parent <= H->Size; parent = child) 105  { 106         child = 2 * parent; /* 从父结点找左孩子 */
107         if(child != H->Size && H->Data[child].Weight > H->Data[child+1].Weight) 108             child++;        /* 有右孩子且比左孩子小, 选右孩子 */
109         if(Temp.Weight < H->Data[child].Weight) 110             break;  /* 原堆最后一个树结点找到位置 */
111         H->Data[parent] = H->Data[child]; /* 孩子结点上滤, 孩子结点覆盖父结点 */
112  } 113     H->Data[parent] = Temp; /* 原堆最后一个树结点归位 */
114     return T; /* 返回原堆第一个树结点 */
115 } 116 
117 /* 建Huffman树 */
118 Tree Huffman(Heap H) 119 { 120     Tree T = NewTreeNode(); /* 临时树结点 */
121     while(H->Size != 1) 122     {    /* 每次取堆中2个最小值建中间树结点 */
123         T->Left = Delete(H); 124         T->Right = Delete(H); 125         T->Weight = T->Left->Weight + T->Right->Weight; 126         
127         Insert(H, *T); /* 复制建立的中间树结点(传参)插入堆 */
128  } 129     free(T); /* 释放临时结点 */
130     T = Delete(H); /* 取出堆中的树 */
131     return T; 132 } 133  
134 /* 带权路径长度 */
135 int WPL(Tree T, int Depth) { /* 整棵树的WPL */
136     if(!T->Left && !T->Right) {  return Depth*T->Weight; } 137     else return WPL(T->Left, Depth+1) + WPL(T->Right, Depth+1); 138 } 139 
140 /* 判断是否正确的Huffman编码 */
141 int Judge(int codelen, int Weight[], int N) 142 { 143     int i, j, wgh; /* 权重wgh*/
144     int flag = 1, count = 1; /* 前缀码, 结点个数 */
145     char ch[2], s[MAXSIZE];     /* 叶结点 编码*/
146     
147     Tree T = NewTreeNode(), t = NULL; /* 树根 */
148     
149     /* 建树*/
150     for(i = 0; i < N; i++)  /* N个叶子 */
151  { 152         t = T; /* 树根 */
153         scanf("%s%s", ch, s); /* 叶结点 编码*/
154         
155         wgh = Weight[ch[0]];  /* 叶结点的权重 */    
156                             
157         for(j = 0; s[j]; j++)/* 由根向叶子建一枝树 */
158  { 159             if(s[j] == '0') { 160                 if(!t->Left){ 161                     t->Left = NewTreeNode(); 162                     count++; 163  } 164                 t = t->Left; 165  } 166             if(s[j] == '1') { 167                 if(!t->Right){ 168                     t->Right = NewTreeNode(); 169                     count++; 170  } 171                 t = t->Right; 172  } 173  } 174         
175         if(t->Left || t->Right){/*不是前缀码*/
176             flag = 0; 177  } 178         else{ 179             t->Weight = wgh; 180  } 181  } 182     
183     /* 前缀码, 结点数, 带权路径长度 */
184     if(!flag || count != 2*N-1 ||codelen != WPL(T, 0)) 185         return 0; 186     return 1; 187 }
 1 /* 
 2  建一个最小堆, 堆插入树结点, 造成树结点森林;  3  每次从堆中取2个最小树结点, 建中间树结点并插入堆;  4  最后堆中森林造成一棵Huffman树并计算WPL;  5  判断给定的叶结点及编码, 是否为正确的编码;  6 */
 7 
 8 #include <stdio.h>
 9 #include <stdlib.h>
 10 #include <string.h>
 11 
 12 /* 二叉树结点 */
 13 typedef struct TreeNode* Tree;  14 struct TreeNode {  15     int Weight;  16  Tree Left, Right;  17 };  18 
 19 /* 堆(优先队列) */
 20 #define MAXSIZE 256 
 21 typedef struct HeapNode* Heap;  22 struct HeapNode {  23     struct TreeNode Data[MAXSIZE];/* 彻底二叉树顺序存储 */
 24     int Size;  25 };  26  
 27 Tree NewTreeNode();/* 建树结点 */
 28 Heap CreatHeap(); /* 建空堆 */
 29 void Insert(Heap H, struct TreeNode T);/* 堆插入 */
 30 Tree Delete(Heap H);/* 堆删除 */
 31 Tree Huffman(Heap H); /* 建Huffman树 */
 32 int WPL(Tree T, int Depth);/* 整棵树的WPL */
 33 
 34 int cnt1 = 0, cnt2 = 0;  /* 结点度为1度为2的全局变量 */
 35 void JudgeTree(Tree T); /* 判断树是否有度为1的结点 */
 36 int Judge(int codelen, int Weight[], int N) ; /* 判断是否正确的Huffman编码 */
 37 
 38 int main()  39 {  40     int N, Weight[MAXSIZE] = {0};  41     char ch;  42    
 43     Heap H = CreatHeap(); /* 建空堆 */
 44     Tree T = NewTreeNode();  /* 建临时树结点 */
 45     
 46     scanf("%d", &N);  /* 树结点个数 */
 47     for(int i = 0; i < N; i++)  48  {  49         scanf(" %c", &ch);  50         scanf("%d", &Weight[ch]);  51         T->Weight = Weight[ch];  52         H->Data[H->Size].Left = H->Data[H->Size].Right = NULL;  53         Insert(H, *T); /* 复制建立的树结点(传参), 插入堆, 造成树森林 */
 54  }  55     
 56     free(T); /* 释放临时结点 */
 57     
 58     T = Huffman(H);   /* 建Huffman树 */
 59     
 60     int codelen = WPL(T, 0); /* 求Huffman树的WPL */    
 61     int M;  /* M棵树 */
 62     scanf("%d", &M);  63     
 64     while(M--)  65     {    /* 一次判断一棵树 */
 66         if(Judge(codelen, Weight, N)) printf("Yes\n");  67         else printf("No\n");  68  }  69     
 70     return 0;  71 }  72 
 73  /* 建树结点 */
 74 Tree NewTreeNode() {  75  Tree T;  76     T = (Tree)malloc(sizeof(struct TreeNode));  77     T->Weight = 0;  78     T->Left = T->Right = NULL;  79     return T;  80 }  81 
 82  /* 建空堆 */
 83 Heap CreatHeap() {  84  Heap H;  85     H = (Heap)malloc(sizeof(struct HeapNode));  86     H->Size = 0;            /* 空堆 */
 87     H->Data[0].Weight = -1; /* 哨兵 */
 88     return H;  89 }  90  
 91  /* 堆插入 */
 92 void Insert(Heap H, struct TreeNode T) {  93     int i = ++H->Size;  /* ++堆, 从堆的最后开始寻找插入结点位置 */
 94     for( ; T.Weight < H->Data[i/2].Weight; i /= 2)  95         H->Data[i] = H->Data[i/2]; /* 父结点下滤 */
 96     H->Data[i] = T; /* 插入结点 */
 97 }  98 
 99  /* 堆删除 */
100 Tree Delete(Heap H) 101 {    /* 提取堆最后一个树结点, 从堆的第一个结点开始比较,上滤, 堆-- */
102     int parent, child; 103     struct TreeNode Temp = H->Data[H->Size--]; /* 提取堆最后一个树结点 */
104     Tree T = NewTreeNode(); /* 建立树结点 */
105     *T = H->Data[1];        /* 从堆中提取第一个树结点 */
106     for(parent = 1; 2*parent <= H->Size; parent = child) 107  { 108         child = 2 * parent; /* 从父结点找左孩子 */
109         if(child != H->Size && H->Data[child].Weight > H->Data[child+1].Weight) 110             child++;        /* 有右孩子且比左孩子小, 选右孩子 */
111         if(Temp.Weight < H->Data[child].Weight) 112             break;  /* 原堆最后一个树结点找到位置 */
113         H->Data[parent] = H->Data[child]; /* 孩子结点上滤, 孩子结点覆盖父结点 */
114  } 115     H->Data[parent] = Temp; /* 原堆最后一个树结点归位 */
116     return T; /* 返回原堆第一个树结点 */
117 } 118 
119 /* 建Huffman树 */
120 Tree Huffman(Heap H) 121 { 122     Tree T = NewTreeNode(); /* 临时树结点 */
123     while(H->Size != 1) 124     {    /* 每次取堆中2个最小值建中间树结点 */
125         T->Left = Delete(H); 126         T->Right = Delete(H); 127         T->Weight = T->Left->Weight + T->Right->Weight; 128         
129         Insert(H, *T); /* 复制建立的中间树结点(传参)插入堆 */
130  } 131     free(T); /* 释放临时结点 */
132     T = Delete(H); /* 取出堆中的树 */
133     return T; 134 } 135  
136 /* 带权路径长度 */
137 int WPL(Tree T, int Depth) { /* 整棵树的WPL */
138     if(!T->Left && !T->Right) {  return Depth*T->Weight; } 139     else return WPL(T->Left, Depth+1) + WPL(T->Right, Depth+1); 140 } 141 
142 /* 判断树是否存在度为1的结点 */
143 void JudgeTree(Tree T) 144 { 145     if(T) { 146         if(T->Left && T->Right) cnt2++; 147         else if(!T->Left && !T->Right) cnt1++; 148         else cnt1 = 0; /* 判断是否存在度为1的结点 */
149         JudgeTree(T->Left); 150         JudgeTree(T->Right); 151  } 152 } 153 
154 /* 判断是否正确的Huffman编码 */
155 int Judge(int codelen, int Weight[], int N) 156 { 157     int i, j, wgh, flag = 1;  /* 编码正确标志flag */
158     char ch[2], s[MAXSIZE]; 159     Tree T = NewTreeNode(), t = NULL; 160     /* 1.建树(2个状况) */
161     for(i = 0; i < N; i++)  /* N个叶子 */
162  { 163         t = T; /* 树根 */
164         scanf("%s%s", ch, s); 165         wgh = Weight[ch[0]]; 166         
167         /* 1.1. 树高超过告终点数*/        
168         if(strlen(s) > N) { 169             flag = 0; 170             break; 171  } 172         
173         /* 1.2. 由根向叶子建树 */            
174         for(j = 0; s[j]; j++) 175  { 176             if(s[j] == '0') { 177                 if(!t->Left) t->Left = NewTreeNode(); 178                 t = t->Left; 179  } 180             if(s[j] == '1') { 181                 if(!t->Right) t->Right = NewTreeNode(); 182                 t = t->Right; 183  } 184             
185             if(!s[j+1]) /* 叶结点权重 */
186  { 187                 if(t->Left || t->Right)/*不是前缀码*/
188  { 189                     flag = 0; 190                     break; 191  } 192                 t->Weight = wgh; 193  } 194  } 195  } 196     
197     /* 1.树高超过告终点数或不是前缀码*/
198     if(!flag) 199         return 0; 200     
201     /* 2.判断是否存在度为1的结点 */
202     cnt1 = cnt2 = 0; 203  JudgeTree(T); 204     if(cnt1 != cnt2 + 1) 205         return 0; 206     
207     /* 3.带权路径长度WPL是否相等*/
208     if(codelen != WPL(T, 0)) 209         return 0; 210     
211     /* 4.编码正确 */
212     return 1; 213 }
 1 /* 
 2  编码的字符是双数个,而提交采用的是等长编码  3  仅判断叶结点和度的算法 测试点5不过  4  须要判断用例与Huffman树的WPL是否相等  5 */
 6 
 7 #include <stdio.h>
 8 #include <stdlib.h>
 9 #include <string.h>
 10 
 11 #define MAXSIZE 256 
 12 
 13 /* 二叉树结点 */
 14 typedef struct TreeNode* Tree;  15 struct TreeNode {  16     int Weight;  17  Tree Left, Right;  18 };  19 
 20 Tree NewTreeNode();/* 建树结点 */
 21 
 22 int cnt1 = 0, cnt2 = 0;  /* 结点度为1度为2的全局变量 */
 23 void JudgeTree(Tree T); /* 判断树是否有度为1的结点 */
 24 int Judge(int Weight[], int N) ; /* 判断是否正确的Huffman编码 */
 25 
 26 int main()  27 {  28     int N, Weight[MAXSIZE] = {0};  29     char ch;  30        
 31     scanf("%d", &N);  /* 树结点个数 */
 32     for(int i = 0; i < N; i++)  33  {  34         scanf(" %c", &ch);  35         scanf("%d", &Weight[ch]);  36  }  37     
 38     int M;  /* M棵树 */
 39     scanf("%d", &M);  40     
 41     while(M--)  42     {    /* 一次判断一棵树 */
 43         if(Judge(Weight, N)) printf("Yes\n");  44         else printf("No\n");  45  }  46     
 47     return 0;  48 }  49 
 50  /* 建树结点 */
 51 Tree NewTreeNode() {  52  Tree T;  53     T = (Tree)malloc(sizeof(struct TreeNode));  54     T->Weight = 0;  55     T->Left = T->Right = NULL;  56     return T;  57 }  58 
 59 /* 判断树是否存在度为1的结点 */
 60 void JudgeTree(Tree T)  61 {  62     if(T) {  63         if(T->Left && T->Right) cnt2++;  64         else if(!T->Left && !T->Right) cnt1++;  65         else cnt1 = 0;  66         JudgeTree(T->Left);  67         JudgeTree(T->Right);  68  }  69 }  70 
 71 int Judge(int Weight[], int N)  72 {  73     int i, j, wgh, flag = 1;  /* 编码正确标志flag */
 74     char ch[2], s[MAXSIZE];  75     Tree T = NewTreeNode(), t = NULL;  76     /* 1.建树(2个状况) */
 77     for(i = 0; i < N; i++)  /* N个叶子 */
 78  {  79         t = T; /* 树根 */
 80         scanf("%s%s", ch, s);  81         wgh = Weight[ch[0]];  82         
 83         /* 1.1. 树高超过告终点数*/        
 84         if(strlen(s) > N) {  85             flag = 0;  86             break; 
 87  }  88         
 89         /* 1.2. 由根向叶子建树 */            
 90         for(j = 0; s[j]; j++)  91  {  92             if(s[j] == '0') {  93                 if(!t->Left) t->Left = NewTreeNode();  94                 t = t->Left;  95  }  96             if(s[j] == '1') {  97                 if(!t->Right) t->Right = NewTreeNode();  98                 t = t->Right;  99  } 100             
101             if(!s[j+1]) /* 叶结点权重 */
102  { 103                 if(t->Left || t->Right)/*不是前缀码*/
104  { 105                     flag = 0; 106                     break; 
107  } 108                 t->Weight = wgh; 109  } 110  } 111  } 112     
113     /* 1.树高超过告终点数或不是前缀码*/
114     if(!flag) 115         return 0; 116     
117     /* 2.判断是否存在度为1的结点 */
118     cnt1 = cnt2 = 0; 119  JudgeTree(T); 120     if(cnt1 != cnt2 + 1) 121         return 0; 122     
123     /* 3.编码正确 */
124     return 1; 125 }

06-图1 列出连通集

给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其全部的连通集。假设顶点从0到N−1编号。进行搜索时,假设咱们老是从编号最小的顶点出发,按编号递增的顺序访问邻接点。

输入格式:

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

输出格式:

按照"{ v1v2... vk}"的格式,每行输出一个连通集。先输出DFS的结果,再输出BFS的结果。

输入样例:

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

输出样例:

{ 0 1 4 2 7 } { 3 5 } { 6 } { 0 1 2 7 4 } { 3 5 } { 6 }
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <stdbool.h>
 4 
 5 /* 定义图 */
 6 #define MaxVertex 100        /* 顶点个数 */
 7 typedef int Vertex;          /* 顶点类型定义 */
 8 int G[MaxVertex][MaxVertex]; /* 图的邻接矩阵 */
 9 int Nv, Ne;                  /* 图的顶点及边 */
 10 bool visit[MaxVertex];       /* 顶点是否访问数组标记 */
 11 
 12 /* 队列结构体(顺序队列) */
 13 #define ERROR -1
 14 typedef struct QNode *Queue;  15 struct QNode {  16     Vertex *Data;     /* 存储元素的数组 */
 17     int Front, Rear;  /* 队列的头、尾指针 */
 18     int MAXSIZE;           /* 队列最大容量 */
 19 };  20 
 21 Queue CreateQueue();  22 bool IsFull( Queue Q );  23 bool AddQ( Queue Q, Vertex X );  24 bool IsEmpty( Queue Q );  25 Vertex DeleteQ( Queue Q );  26 
 27 void BuildGraph();       /* 建图 */
 28 void DFS(Vertex v); /* DFS */
 29 void BFS(Vertex v); /* BFS */
 30 void PrintConnectedSet(void(*Traverse)(Vertex));  /* 遍历联通集 */
 31 
 32 int main()  33 {  34  BuildGraph();  35  PrintConnectedSet(DFS);  36  PrintConnectedSet(BFS);  37     return 0;  38 }  39 
 40 Queue CreateQueue()  41 {  42     Queue Q = (Queue)malloc(sizeof(struct QNode));  43     Q->Data = (Vertex *)malloc(MAXSIZE * sizeof(Vertex));  44     Q->Front = Q->Rear = 0;  45     Q->MAXSIZE = MaxVertex;  46     return Q;  47 }  48  
 49 bool IsFull( Queue Q )  50 {  51     return ((Q->Rear+1)%Q->MAXSIZE == Q->Front);  52 }  53  
 54 bool AddQ( Queue Q, Vertex X )  55 {  56     if ( IsFull(Q) ) {  57         return false;  58  }  59     else {  60         Q->Rear = (Q->Rear+1)%Q->MAXSIZE;  61         Q->Data[Q->Rear] = X;  62         return true;  63  }  64 }  65  
 66 bool IsEmpty( Queue Q )  67 {  68     return (Q->Front == Q->Rear);  69 }  70  
 71 Vertex DeleteQ( Queue Q )  72 {  73     if ( IsEmpty(Q) ) {  74         return ERROR;  75  }  76     else {  77         Q->Front =(Q->Front+1)%Q->MAXSIZE;  78         return  Q->Data[Q->Front];  79  }  80 }  81 
 82 /* 建图 */
 83 void BuildGraph()  84 {  85     scanf("%d", &Nv);  86     for(int i=0; i<Nv; ++i)  87  {  88         visit[i] = false;  /* 图的顶点置为未访问 */
 89         for(int j=0; j<Nv; j++)  90             G[i][j] = 0;   /* 图的顶点之间置为未链接 */        
 91  }  92     scanf("%d", &Ne);       /* 输入图的边, 顶点对 */
 93     for(int i=0; i<Ne; i++)  94  {  95  Vertex v1, v2;  96         scanf("%d%d", &v1, &v2);  97         G[v1][v2] = 1;  98         G[v2][v1] = 1;      /* 无向图 */
 99  } 100 } 101 
102 /* DFS */
103 void DFS(Vertex v) 104 { 105     visit[v] = true; /* 标记已访问 */
106     printf(" %d", v); 107     for(Vertex i=0; i<Nv; i++) /* 与该顶点邻接的顶点 */
108         if(!visit[i] && G[v][i]) 109  DFS(i); 110 } 111 
112 /* BFS */
113 void BFS(Vertex v) 114 { 115     Queue q = CreateQueue(); /* 建队列 */
116     visit[v] = true;         /* 访问顶点 */
117     printf(" %d", v); 118     AddQ(q,v);               /* 顶点入队 */
119     while(!IsEmpty(q)) 120  { 121         Vertex t = DeleteQ(q); /* 出队队首元素 */ 
122         for(Vertex i=0; i<Nv; ++i) /* 与该顶点邻接的顶点 */
123  { 124             if(!visit[i] && G[t][i]) /* 未访问的邻接顶点 */
125  { 126                 visit[i] = true; /* 访问顶点 */
127                 printf(" %d", i); 128                 AddQ(q,i);       /* 顶点入队 */
129  } 130  } 131  } 132 } 133 
134 /* 遍历联通集 */
135 void PrintConnectedSet(void(*Traverse)(Vertex)) 136 { 137     for(Vertex i=0; i<Nv; ++i) /*遍历顶点 */
138  { 139         if(!visit[i]){ 140             printf("{"); 141             Traverse(i); /* DFS, BFS */
142             printf(" }\n"); 143  } 144  } 145     for(Vertex i=0;i<Nv;i++) /* 顶点恢复未访问 */
146         visit[i] = false; 147 }

06-图2 Saving James Bond - Easy Version

This time let us consider the situation in the movie "Live and Let Die" in which James Bond, the world's most famous spy, was captured by a group of drug dealers. He was sent to a small piece of land at the center of a lake filled with crocodiles. There he performed the most daring action to escape -- he jumped onto the head of the nearest crocodile! Before the animal realized what was happening, James jumped again onto the next big head... Finally he reached the bank before the last crocodile could bite him (actually the stunt man was caught by the big mouth and barely escaped with his extra thick boot).

Assume that the lake is a 100 by 100 square one. Assume that the center of the lake is at (0,0) and the northeast corner at (50,50). The central island is a disk centered at (0,0) with the diameter of 15. A number of crocodiles are in the lake at various positions. Given the coordinates of each crocodile and the distance that James could jump, you must tell him whether or not he can escape.

Input Specification:

Each input file contains one test case. Each case starts with a line containing two positive integers N (≤100), the number of crocodiles, and D, the maximum distance that James could jump. Then N lines follow, each containing the (x,y) location of a crocodile. Note that no two crocodiles are staying at the same position.

Output Specification:

For each test case, print in a line "Yes" if James can escape, or "No" if not.

Sample Input 1:

14 20
25 -15
-25 28
8 49
29 15
-35 -2
5 28
27 -29
-8 -28
-20 -35
-25 -20
-13 29
-30 15
-35 40
12 12

Sample Output 1:

Yes

Sample Input 2:

4 13
-12 12
12 12
-12 -12
12 -12

Sample Output 2:

No
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <math.h>
 4 #include <stdbool.h>
 5 
 6 /* 鳄鱼结点 */
 7 #define MaxVertexNum 101
 8 struct Node{  9     int x;    /* 横坐标 */
10     int y;    /* 纵坐标 */
11     bool visit;       /* 是否被访问 */
12     bool toshore;     /* 是否能上岸 */
13 }; 14 
15 int N;    /* 鳄鱼数 */ 
16 int D;    /* 跳跃距离 */
17 struct Node G[MaxVertexNum]; /* 鳄鱼图 */
18 bool Escape = false; /* 逃离 */
19 
20 void Init();/* 图初始化 */ 
21 bool Shore(int x, int y, double d); /* 可否到岸 */
22 bool Jump(int x1, int y1, int x2, int y2, double d); /* 可否跳上去 */
23 void DFS(int v);  /* 深搜 */
24 void listCompoent();/* 遍历全部第一步能跳到的鳄鱼 */
25 
26 int main() 27 { 28  Init(); 29  listCompoent(); 30     return 0; 31 } 32 
33 void Init() 34 { 35     scanf("%d%d", &N, &D); 36     int x,y; 37     for(int i=0;i<N;i++) 38  { 39         scanf("%d%d", &x, &y); 40         G[i].x = x; 41         G[i].y = y; 42         G[i].visit = false; 43         G[i].toshore = false; 44         if(Shore(x,y,D)) G[i].toshore = true; 45  } 46 } 47 
48 bool Shore(int x, int y, double d){ 49     return abs(x-50)<=d || abs(x+50)<=d || abs(y+50)<=d || abs(y-50) <= d; 50 } 51 
52 bool Jump(int x1, int y1, int x2, int y2, double d){ 53     return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) <= d; 54 } 55 
56 void DFS(int v) 57 { 58     if(G[v].toshore){ 59         Escape = true; 60         return; 61  } 62     G[v].visit = true; 63     for(int i=0; i<N; i++){  /* 没被访问且能够跳上去的鳄鱼v to i */
64         if(!G[i].visit && Jump(G[v].x, G[v].y, G[i].x, G[i].y, D)) 65  DFS(i); 66  } 67 } 68 
69 void listCompoent() 70 { 71     for(int i=0; i<N; i++) 72  { 73         if(Jump(G[i].x, G[i].y, 0, 0, D+15/2)) /* first jump */
74  { 75  DFS(i); 76  } 77  } 78     if(Escape) 79         printf("Yes\n"); 80     else
81         printf("No\n"); 82 }

06-图3 六度空间

“六度空间”理论又称做“六度分隔(Six Degrees of Separation)”理论。这个理论能够通俗地阐述为:“你和任何一个陌生人之间所间隔的人不会超过六个,也就是说,最多经过五我的你就可以认识任何一个陌生人。”如图所示。

 

“六度空间”理论虽然获得普遍的认同,而且正在获得愈来愈多的应用。可是数十年来,试图验证这个理论始终是许多社会学家努力追求的目标。然而因为历史的缘由,这样的研究具备太大的局限性和困难。随着当代人的联络主要依赖于电话、短信、微信以及因特网上即时通讯等工具,可以体现社交网络关系的一手数据已经逐渐使得“六度空间”理论的验证成为可能。

 假如给你一个社交网络图,请你对每一个节点计算符合“六度空间”理论的结点占结点总数的百分比。

输入格式:

输入第1行给出两个正整数,分别表示社交网络图的结点数N(1<N≤103,表示人数)、边数M(≤33×N,表示社交关系数)。随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个结点的编号(节点从1到N编号)。

输出格式:

对每一个结点输出与该结点距离不超过6的结点数占结点总数的百分比,精确到小数点后2位。每一个结节点输出一行,格式为“结点编号:(空格)百分比%”。

输入样例:

10 9
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10

输出样例:

1: 70.00%
2: 80.00%
3: 90.00%
4: 100.00%
5: 100.00%
6: 100.00%
7: 100.00%
8: 90.00%
9: 80.00%
10: 70.00%
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <stdbool.h>
 4 
 5 /* 邻接表结点 */
 6 #define MaxVertex 10005
 7 typedef int Vertex;  8 typedef struct Node *AdjList;  9 struct Node{  10     Vertex Adjv;   /* 顶点 */
 11  AdjList Next;  12 };  13 
 14 AdjList G[MaxVertex];    /* 邻接表数组 */
 15 bool visit[MaxVertex];   /* 是否访问 */ 
 16 int N;   /* 结点数 */
 17 int M;   /* 边数 */
 18 
 19 /* 队列结构体(顺序队列) */
 20 #define ERROR -1
 21 typedef struct QNode *Queue;  22 struct QNode {  23     Vertex *Data;     /* 存储元素的数组 */
 24     int Front, Rear;  /* 队列的头、尾指针 */
 25     int MAXSIZE;           /* 队列最大容量 */
 26 };  27 
 28 Queue CreateQueue();  29 bool IsFull( Queue Q );  30 bool AddQ( Queue Q, Vertex X );  31 bool IsEmpty( Queue Q );  32 Vertex DeleteQ( Queue Q );  33 
 34 void InitVisit(); /* 访问状态初始值 */
 35 void Init(); /* 初始化 */
 36 int BFS(Vertex v);  37 void output(double result,int i);  38 void SDS();  39 
 40 int main()  41 {  42  Init();  43  SDS();  44     return 0;  45 }  46 
 47 Queue CreateQueue()  48 {  49     Queue Q = (Queue)malloc(sizeof(struct QNode));  50     Q->Data = (Vertex *)malloc(MaxVertex * sizeof(Vertex));  51     Q->Front = Q->Rear = 0;  52     Q->MAXSIZE = MaxVertex;  53     return Q;  54 }  55  
 56 bool IsFull( Queue Q )  57 {  58     return ((Q->Rear+1)%Q->MAXSIZE == Q->Front);  59 }  60  
 61 bool AddQ( Queue Q, Vertex X )  62 {  63     if ( IsFull(Q) ) {  64         return false;  65  }  66     else {  67         Q->Rear = (Q->Rear+1)%Q->MAXSIZE;  68         Q->Data[Q->Rear] = X;  69         return true;  70  }  71 }  72  
 73 bool IsEmpty( Queue Q )  74 {  75     return (Q->Front == Q->Rear);  76 }  77  
 78 Vertex DeleteQ( Queue Q )  79 {  80     if ( IsEmpty(Q) ) {  81         return ERROR;  82  }  83     else {  84         Q->Front =(Q->Front+1)%Q->MAXSIZE;  85         return  Q->Data[Q->Front];  86  }  87 }  88 
 89 void InitVisit(){ /* 访问状态初始值 */
 90     for(int i=1; i<=N; ++i)  91         visit[i] = false;  92 }  93 
 94 void Init() /* 初始化 */
 95 {  96  Vertex v1,v2;  97  AdjList NewNode;  98     scanf("%d%d", &N, &M);  99     
100     for(int i=1; i<=N; ++i){  /* 邻接表初始化 1—N */
101         G[i] = (AdjList)malloc(sizeof(struct Node)); 102         G[i]->Adjv = i;     /* 邻接表下标 */
103         G[i]->Next = NULL;  /* 邻接表指针 */
104  } 105 
106     for(int i=0; i<M; ++i){  /* 边初始值 */
107         scanf("%d%d", &v1, &v2); 108         
109         NewNode = (AdjList)malloc(sizeof(struct Node)); 110         NewNode->Adjv = v2;         /* 新结点 */
111         
112         NewNode->Next = G[v1]->Next; /* 连接 */
113         G[v1]->Next = NewNode; 114         
115         NewNode = (AdjList)malloc(sizeof(struct Node)); 116         NewNode->Adjv = v1;          /* 新结点 */
117         
118         NewNode->Next = G[v2]->Next; /* 连接 */
119         G[v2]->Next = NewNode; 120  } 121 } 122 
123 int BFS(Vertex v) 124 { 125     Queue q = CreateQueue(); 126  Vertex t; 127     int level = 0; 128     int last = v;     /* 该层最后一次访问的结点 */ 
129     int tail = v;     /* 每次在变的结点 */ 
130     AdjList node;     /* 邻接表结点 */
131     visit[v] = true; 132     int count = 1;    /* 统计关系数 */ 
133     AddQ(q,v);        /* 顶点入队 */
134     while(!IsEmpty(q)) 135  { 136         t = DeleteQ(q);   /* 顶点出队 */
137 
138         node = G[t]->Next; /* G[i]第一个结点存本身的下标 */
139         while(node) 140  { 141             if(!visit[node->Adjv]){ 142                 visit[node->Adjv] = true; 143                 AddQ(q, node->Adjv); 144                 count++; 145                 tail = node->Adjv; /* 每次更新该结点 */
146  } 147             node = node->Next; 148  } 149     
150         if(t == last){  /* 若是该当前结点是这层最后一个结点 */
151             level++;      /* 层数 +1 */  
152             last = tail;  /* 更改 last */
153  } 154         
155         if(level==6)  /* 6层结束 */
156            break; 157  } 158     return count; 159 } 160 
161 
162 void output(double result, int i){ 163     printf("%d: %.2f%%\n", i, result); 164 } 165 
166 void SDS()  /* 六度空间搜索 six degree search */
167 { 168     int count; 169     for(int i=1; i<=N; i++){ 170         InitVisit();     /* 每次初始化访问数组 */
171         count = BFS(i);   /* 搜索结果, 结点数count */
172         output((100.0*count)/N, i); 173  } 174 }

07-图4 哈利·波特的考试

哈利·波特要考试了,他须要你的帮助。这门课学的是用魔咒将一种动物变成另外一种动物的本事。例如将猫变成老鼠的魔咒是haha,将老鼠变成鱼的魔咒是hehe等等。反方向变化的魔咒就是简单地将原来的魔咒倒过来念,例如ahah能够将老鼠变成猫。另外,若是想把猫变成鱼,能够经过念一个直接魔咒lalala,也能够将猫变老鼠、老鼠变鱼的魔咒连起来念:hahahehe。

如今哈利·波特的手里有一本教材,里面列出了全部的变形魔咒和能变的动物。老师容许他本身带一只动物去考场,要考察他把这只动物变成任意一只指定动物的本事。因而他来问你:带什么动物去可让最难变的那种动物(即该动物变为哈利·波特本身带去的动物所须要的魔咒最长)须要的魔咒最短?例如:若是只有猫、鼠、鱼,则显然哈利·波特应该带鼠去,由于鼠变成另外两种动物都只须要念4个字符;而若是带猫去,则至少须要念6个字符才能把猫变成鱼;同理,带鱼去也不是最好的选择。

输入格式:

输入说明:输入第1行给出两个正整数N (≤100)和M,其中N是考试涉及的动物总数,M是用于直接变形的魔咒条数。为简单起见,咱们将动物按1~N编号。随后M行,每行给出了3个正整数,分别是两种动物的编号、以及它们之间变形须要的魔咒的长度(≤100),数字之间用空格分隔。

输出格式:

输出哈利·波特应该带去考场的动物的编号、以及最长的变形魔咒的长度,中间以空格分隔。若是只带1只动物是不可能完成全部变形要求的,则输出0。若是有若干只动物均可以备选,则输出编号最小的那只。

输入样例:

6 11
3 4 70
1 2 1
5 4 50
2 6 50
5 6 60
1 3 70
4 6 60
3 6 80
5 1 100
2 4 60
5 2 80

输出样例:

4 70
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define MaxVertexNum 100 /* 最大顶点数设为100 */ 
 5 #define INFINITY 65535   /* ∞设为双字节无符号整数的最大值65535*/ 
 6 typedef int Vertex;      /* 用顶点下标表示顶点,为整型*/ 
 7 typedef int WeightType;  /* 边的权值设为整型*/ 
 8 
 9 /* 边的定义*/ 
 10 typedef struct ENode* PtrToENode;  11 struct ENode{  12     Vertex V1, V2;      /* 有向边<V1, V2> */ 
 13     WeightType Weight;  /* 权重*/ 
 14 };  15 typedef PtrToENode Edge; /* 边类型 边结构体指针 */
 16 
 17 /* 图结点的定义*/ 
 18 typedef struct GNode* PtrToGNode;  19 struct GNode{  20     int Nv;  /* 顶点数*/ 
 21     int Ne;  /* 边数*/ 
 22     WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵*/     
 23 };  24 typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 图结构体指针*/
 25 
 26 MGraph CreateGraph( int VertexNum);/* 初始化一个有VertexNum个顶点但没有边的图*/  
 27 void InsertEdge( MGraph Graph, Edge E );/* 插入边<V1, V2> */  
 28 MGraph BuildGraph();  /* 1 */
 29 
 30 void Floyd( MGraph Graph, WeightType D[][MaxVertexNum] ); /* 弗洛伊德算法 */
 31 WeightType FindMaxDist( WeightType D[][MaxVertexNum], Vertex i, int N );  32 void FindAnimal( MGraph Graph ); /* 2 */
 33 
 34 int main()  35 {  36     MGraph G = BuildGraph();  37  FindAnimal( G );  38     return 0;  39 }  40 
 41 MGraph CreateGraph( int VertexNum)  42 { /* 初始化一个有VertexNum个顶点但没有边的图*/ 
 43     Vertex V, W;    /* 顶点V W */
 44     MGraph Graph;   /* 图指针 */
 45     Graph = (MGraph)malloc(sizeof(struct GNode)); /* 创建图*/ 
 46     Graph->Nv = VertexNum;  /* 图顶点数 */
 47     Graph->Ne = 0;          /* 没有边 */   
 48     /* 初始化邻接矩阵*/ 
 49     /* 注意:这里默认顶点编号从0开始,到(Graph->Nv-1) */ 
 50     for(V=0; V<Graph->Nv; V++)  51         for(W=0; W<Graph->Nv; W++)  52             Graph->G[V][W] = INFINITY;  /* 顶点之间没有边 */
 53     return Graph;  54 }  55 
 56 void InsertEdge( MGraph Graph, Edge E ) /* 插入边<V1, V2> */  
 57 {     /* 如果无向图,还要插入边<V2, V1> */ 
 58     Graph->G[E->V1][E->V2] = E->Weight;  59     Graph->G[E->V2][E->V1] = E->Weight;  60 }  61 
 62 MGraph BuildGraph()  63 {  64  MGraph Graph;  65  Edge E;  66     int Nv, i;  67     scanf("%d", &Nv);            /* 读入顶点个数*/ 
 68     Graph = CreateGraph(Nv);     /* 初始化有Nv个顶点但没有边的图*/
 69     scanf("%d", &(Graph->Ne));   /* 读入边数*/ 
 70     if( Graph->Ne != 0 ) {       /* 若是有边*/ 
 71         E = (Edge)malloc(sizeof(struct ENode)); /* 创建边结点*/ 
 72         /* 读入边,格式为"起点终点权重",插入邻接矩阵*/ 
 73         for(i=0; i<Graph->Ne; i++) {  74             scanf("%d %d %d", &E->V1, &E->V2, &E->Weight);  75             E->V1--; E->V2--;  /* 起始编号从0开始 */
 76  InsertEdge( Graph, E );  77  }  78  }  79     return Graph;  80 }  81 
 82 void Floyd( MGraph Graph, WeightType D[][MaxVertexNum] )  83 {  84  Vertex i, j, k;  85     /* 初始化*/ 
 86     for( i=0; i<Graph->Nv; i++ )  87         for( j=0; j<Graph->Nv; j++ ) {  88             D[i][j] = Graph->G[i][j];  89  }  90     for( k=0; k<Graph->Nv; k++ )  91         for( i=0; i<Graph->Nv; i++ )  92             for( j=0; j<Graph->Nv; j++ )  93                 if( D[i][k] + D[k][j] < D[i][j] ) {  94                     D[i][j] = D[i][k] + D[k][j];  95  }  96 }  97 
 98 void FindAnimal( MGraph Graph )  99 { 100  WeightType D[MaxVertexNum][MaxVertexNum], MaxDist, MinDist; 101  Vertex Animal, i; 102     
103     Floyd( Graph, D ); /* 多源最短路径 */
104     
105     MinDist= INFINITY; 106     for( i=0; i<Graph->Nv; i++ ) { 107         MaxDist= FindMaxDist( D, i, Graph->Nv);  /* 第i行的最大值 */
108         if( MaxDist== INFINITY ) { /* 说明有从i没法变出的动物*/ 
109             printf("0\n"); 110             return; 111  } 112         if( MinDist > MaxDist) { /* 找到最长距离更小的动物*/ 
113             MinDist = MaxDist; 114             Animal = i+1; /* 更新距离,记录编号*/ 
115  } 116  } 117     printf("%d %d\n", Animal, MinDist); 118 } 119 
120 WeightType FindMaxDist( WeightType D[][MaxVertexNum], Vertex i, int N ) 121 { 122  WeightType MaxDist; 123  Vertex j; 124     MaxDist= 0; 125     for( j=0; j<N; j++ ) /* 找出i到其余动物j的最长距离*/ 
126         if( i!=j && D[i][j]>MaxDist) /* i==j 对角元的值INFINITY */
127             MaxDist = D[i][j];   /* 第i行的最大值 */
128     return MaxDist; 129 }

下一题预留空格

相关文章
相关标签/搜索