1.最大子列和输出(按在线算法)
#include<stdio.h> #include<stdlib.h> #define MAXNUM 100000 int main() { int a[MAXNUM]; int i, k; int thisnum, maxnum; thisnum = 0; maxnum = 0; scanf("%d", &k); for (i = 0; i < k; i++){ scanf("%d", &a[i]); } for (i = 0; i < k;i++){ thisnum += a[i]; if(thisnum>maxnum) maxnum = thisnum; if(thisnum<0) thisnum = 0; } printf("%d", maxnum); //system("pause"); return 0; }
2.最大子列和 输出最大和,起始和末尾数字
#include<stdio.h> #include<stdlib.h> #define MAXNUM 100000 int main() { int a[MAXNUM]; int i, k; int thisnum, maxnum; int start, end, head, tail; thisnum = 0; maxnum = 0; start = 0; end = 0; head = 0; tail = 0; scanf("%d", &k); for (i = 0; i < k; i++){ scanf("%d", &a[i]); } for (i = 0; i < k;i++){ thisnum += a[i]; if(thisnum>=0){ end=i; } if(thisnum==maxnum&&maxnum==0){ head = start; tail = end; } if(thisnum>maxnum){ maxnum = thisnum; head = start; tail = end; } if(thisnum<0){ thisnum = 0; start = i + 1; end = i + 1; } } if(head==tail&&a[head]<0){ head = 0; tail = k - 1; } printf("%d %d %d", maxnum,a[head],a[tail]); //system("pause"); return 0; }
3.BinarySearch
#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; } /* 你的代码将被嵌在这里 */ Position BinarySearch( List L, ElementType X ) { Position left = 1; Position right = L->Last; Position mid; while(left<=right)//如果区间不为空就继续查找 { mid=left+(right-left)/2;//取查找区间正中元素的下标 if(X==L->Data[mid]) return mid; else if(X>L->Data[mid]) left=mid+1;//设置新的查找区间的左端点 else right=mid-1;//设置新的查找区间的右端点 } return NotFound; }