题目描述
跳房子,也叫跳飞机,是一种世界性的儿童游戏。
游戏参与者需要分多个回合按顺序跳到第 1 格直到房子的最后一格。跳房子的过程中,可以向前跳,也可以向后跳。
假设房子的总格数是 count,小红每回合可能连续跳的步教都放在数组 steps 中,请问数组中是否有一种步数的组合,可以让小红两个回合跳到量后一格?
如果有,请输出索引和最小的步数组合。
注意:
数组中的步数可以重复,但数组中的元素不能重复使用。
提供的数据保证存在满足题目要求的组合,且索引和最小的步数组合是唯一的。
输入描述
第一行输入为房子总格数 count,它是 int 整数类型。
第二行输入为每回合可能连续跳的步数,它是 int 整数数组类型。
输出描述
返回索引和最小的满足要求的步数组合(顺序保持 steps 中原有顺序)
补充说明
count ≤ 1000,0 ≤ steps.length ≤ 5000,-100000000 ≤ steps ≤ 100000000
示例一
输入
[1,4,5,2,2]
7
        输出
[5,2]
        示例二
输入
[-1,2,4,9,6]
8
        输出
[-1,9]
        说明
此样例有多种组合满足两回合跳到最后,譬如: [-1,9],[2,6],其中[−1,9]的索引和为 0+3=3,[2,6]的索和为 1+4=5,所以索引和最小的步数组合[−1,9]
代码
            
            
              c
              
              
            
          
          #include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 2000
#define CNT_MAX 1000
int main() {
    char input[MAX_LEN];
    fgets(input, MAX_LEN, stdin);
    input[strcspn(input, "\n")] = '\0';
    int count[1000];
    int n = 0;
    char *token = strtok(input, " ,[]\n");
    while (token != NULL) {
        count[n++] = atoi(token);
        token = strtok(NULL, " ,[]\n");
    }
    int step;
    scanf("%d", &step);
    int min[2];
    min[0] = 0;
    min[1] = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (count[i] + count[j] == step) {
                if ((min[0] == 0 && min[1] == 0) || (i + j < min[0] + min[1])) {
                    min[0] = i;
                    min[1] = j;
                }
            }
        }
    }
    printf("[%d,%d]", count[min[0]], count[min[1]]);
    return 0;
}
        