任务调度算法

题目描述

某分布式任务调度系统有 taskNum 个任务(编号从 1 到 taskNum)需要调度,调度策略:

任务之间可能存在依赖关系,且无循环依赖,如任务1 依赖任务2,那么要等待任务2执行完才能执行任务1;
如果任务之间没有依赖关系,则可以并发执行(假设并发所需资源是充足的)。
现给出任务间的依赖关系,并假设每个任务的执行时间恒为 1 分钟,请计算执行完这 taskNum 个任务所需的最短时间(单位分钟)。

解答要求

时间限制:2000ms, 内存限制:256MB

输入

第一行为任务的数量 taskNum ,其值范围为:[1, 1000]
第二行为依赖关系的数量 relationsNum ,其值范围:[0, 500000]
接下来 relationsNum 行,每行描述一个依赖关系,格式为 IDi>IDj,表示任务 i 依赖任务 j ,IDi 和 IDj 值的范围为:[1, taskNum]

输出

一个整数,代表执行完所有任务的最短时间。

样例

输入样例 1

3
1
1>2

输出样例 1

2

提示样例 1

总共三个任务,任务1依赖任务2,任务2、任务3可以并发执行,最后执行任务1,最短时间为2分钟。

输入样例 2

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

输出样例 2

4

Java算法源码

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Scanner;

public class TaskDispatch {
    // 待实现函数,在此函数中填入答题代码
    private static int getMinTime(int taskNum, int[][] relations) {
        // 动态规划
        int[] dp = new int[taskNum + 1];
        Arrays.fill(dp, 1);
        for (int i = 0; i < taskNum; i++) {
            for (int[] relation : relations) {
                dp[relation[0]] = Math.max(dp[relation[0]], dp[relation[1]] + 1);
            }
        }
        return Arrays.stream(dp).max().getAsInt();
    }

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in, StandardCharsets.UTF_8.name());
        int taskNum = cin.nextInt();
        int relationNum = cin.nextInt();
        int[][] relations = new int[relationNum][];
        if (relationNum > 0) {
            cin.nextLine();
            for (int i = 0; i < relationNum; i++) {
                String[] str = cin.nextLine().split(">");
                relations[i] = new int[2];
                relations[i][0] = Integer.parseInt(str[0]);
                relations[i][1] = Integer.parseInt(str[1]);
            }
        }
        cin.close();

        System.out.println(getMinTime(taskNum, relations));
    }
}
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

软软的铲屎官

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值