KS24. 求x到y的最少计算次数
描述
输入描述
输入以英文逗号分隔的两个数字,数字均在32位整数范围内。输出描述
输出一个数字示例1
输入:
3,11
输出:
3
C 解法, 执行用时: 2ms, 内存消耗: 372KB, 提交时间: 2020-05-20
#include <stdio.h> #include <stdlib.h> int main() { int a,b; scanf("%d,%d",&a,&b); if(a>b){ printf("%d\n",a-b); return 0; } int queue[300]; int visit[200] = {0}; int front = -1; int rear = -1; int length = 0; int qsize = 0; queue[++rear] = a; while(front != rear){ length++; qsize = rear - front; while(qsize-- > 0){ int tmp = queue[++front]; if(tmp == b){ printf("%d\n",length-1); return 0; } if(visit[tmp+100] == 0){ visit[tmp+100] = 1; queue[++rear] = tmp+1; queue[++rear] = tmp-1; queue[++rear] = tmp*2; } } } return 0; }
C 解法, 执行用时: 2ms, 内存消耗: 372KB, 提交时间: 2020-05-14
#include <stdio.h> #include <stdlib.h> int main() { int a,b; scanf("%d,%d",&a,&b); if(a>b){ printf("%d\n",a-b); return 0; } int queue[300]; int visit[200] = {0}; int front = -1; int rear = -1; int length = 0; int qsize = 0; queue[++rear] = a; while(front != rear){ length++; qsize = rear - front; while(qsize-- > 0){ int tmp = queue[++front]; if(tmp == b){ printf("%d\n",length-1); return 0; } if(visit[tmp+100] == 0){ visit[tmp+100] = 1; queue[++rear] = tmp+1; queue[++rear] = tmp-1; queue[++rear] = tmp*2; } } } return 0; }