华为机试C语言-找到比自己强的人数

题目描述:https://pycoder.blog.csdn.net/article/details/127216746?spm=1001.2014.3001.5502
https://blog.csdn.net/qq_27695659/article/details/125882686

这道题一直再想有没有更好的方法,很遗憾,没能想出来。因为相邻的两层递归无法建立联系,当前老师比自己强的人数无法从徒弟的身上找到答案,中间的减枝无法去掉,不清楚是否会超时,时间复杂度还是挺高的。供大家参考吧,有更好的解法欢迎大家赐教~

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int dfs(int map[100][2], int size, int target, int teacher, int cnt) {
    for (int i = 0; i < size; i++) {
        if (map[i][0] == teacher) {
            if (map[i][1] < target) {
                cnt++;
            }
            cnt += dfs(map, size, target, map[i][1], 0);
        }
    }

    return cnt;
}

int main(void) {
    char str[1000] = {0};
    int row = 0, col = 0;
    int index = 0;
    int map[100][2] = {0};
    int max = 0;
    int res[100];

    scanf("%s", str);

    int left, right, len;
    char node[100];
    char* tmp;
    int teacher, student;
    for (int i = 1; i < strlen(str) - 1; i++) {
        if (str[i] == '[') {
            left = i + 1;
        } else if (str[i] == ']') {
            right = i - 1;
            len = right - left + 1;
            strncpy(node, &str[left], len);
            node[len] = '\0';
            printf("%s\n", node);

            tmp = strtok(node, ",");
            teacher = atoi(tmp);
            tmp = strtok(NULL, ",");
            student = atoi(tmp);

            map[index][0] = teacher;
            map[index++][1] = student;
            max = fmax(max, teacher);
            max = fmax(max, student);
        }
    }

    for (int i = 1; i <= max; i++) {
        res[i] = dfs(map, index, i, i, 0);
    }

    printf("[");
    for (int i = 1; i < max; i++) {
        printf("%d,", res[i]);
    }
    printf("%d]\n", res[max]);


    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值