筆試中的流程控制題

最近做到了兩個筆試中的這種題目,這裏備註一下

大概就是需要你維護一個隊列,然後根據一個什麼過程模擬這個流程的進行

一個是華爲筆試的題目:

 

 

 

 

 

 

這道題實際上就是維護一個隊列,然後查表

然而題意確實很複雜,寫輸入輸出也要很久,總的來說還是很難搞

import java.util.*;

public class Solution2 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String[] timeStr=sc.nextLine().split(",");
        //存第一行數據
        List<Integer> list=new ArrayList<>();
        for(int i=0;i<timeStr.length;i++)
        {
            list.add(Integer.parseInt(timeStr[i]));
        }

        //存第二行數據
        String[] relyStr=sc.nextLine().split(",");
        List<Integer[]> table=new ArrayList<>();
        for(String str:relyStr)
        {
            Integer[] rely=new Integer[2];
            rely[0]=Integer.parseInt(str.split("->")[0]);
            rely[1]=Integer.parseInt(str.split("->")[1]);
            table.add(rely);
        }
        //輸出代碼
        Solution2 solution2=new Solution2();
        List<Integer> resultList=solution2.solve2(list,table);
        for(int i=0;i<resultList.size();i++)
        {
            System.out.print(resultList.get(i));
            if(i!=resultList.size()-1)
            {
                System.out.print(",");
            }
        }

    }

    public List<Integer> solve2(List<Integer> time,List<Integer[]> table) {
        //time 時間表

        List<Integer> result = new ArrayList<>(time);//結果表
        HashSet<Integer> set = new HashSet<>();//已經執行完了嗎
        Queue<Integer> line = new LinkedList<>();//排隊表
        for (int i = 0; i < result.size(); i++) {
            line.add(i);//先進先出,序號爲1的任務先執行
        }

        while (line.size() != 0) {
            int flag = 0;
            int test = line.poll();
            for (Integer[] fire : table) {
                if (fire[0] == test) {
                    if (!set.contains(fire[1])) {
                        line.add(test);
                        flag = 1;
                        break;
                    }
                }
            }
            if (flag == 0) {
                set.add(test);
                //都執行過了,該任務可以執行
                for (int i = 0; i < result.size(); i++) {
                    if (!set.contains(i)) {
                        result.set(i, result.get(i) + time.get(test));//每一個未執行過的都要加上剛剛的執行時間
                    }
                }
            }
        }
        return result;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章