公司共有 n 個項目和 m 個小組,每個項目要不無人接手,要不就由 m 個小組之一負責。
group[i] 表示第 i 個項目所屬的小組,如果這個項目目前無人接手,那么 group[i] 就等于 -1。(項目和小組都是從零開始編號的)小組可能存在沒有接手任何項目的情況。
請你幫忙按要求安排這些項目的進度,并返回排序后的項目列表:
同一小組的項目,排序后在列表中彼此相鄰。
項目之間存在一定的依賴關系,我們用一個列表 beforeItems 來表示,其中 beforeItems[i] 表示在進行第 i 個項目前(位于第 i 個項目左側)應該完成的所有項目。
如果存在多個解決方案,只需要返回其中任意一個即可。如果沒有合適的解決方案,就請返回一個 空列表 。
示例 1:
輸入:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
輸出:[6,3,4,1,5,2,0,7]
代碼
class Solution {public int[] sortItems(int n, int m, int[] group, List<List<Integer>> beforeItems) {List<List<Integer>> groupItems=new ArrayList<>();//組-項目的映射List<Integer> groupId=new ArrayList<>();//組的idList<List<Integer>> groupEdges=new ArrayList<>();//組-組的圖for(int i=0;i<n+m;i++){groupItems.add(new ArrayList<>());groupId.add(i);groupEdges.add(new ArrayList<>());}List<List<Integer>> itemEdges=new ArrayList<>();//項目-項目int lastGroup=m;for(int j=0;j<n;j++)//構造 組和項目之間的映射關系{itemEdges.add(new ArrayList<>());if(group[j]==-1)//無人接收的項目,放在id序列的最后n個,并且假設其有一個組接收{group[j]=lastGroup;lastGroup++;}groupItems.get(group[j]).add(j);}int[] itemDegree=new int[n];//對于每個項目的入度表int[] groupDegree=new int[m+n];//對于每個組的入度表for(int k=0;k<beforeItems.size();k++)//根據先后關系構造組-組圖 以及項目-項目的圖{int cur=group[k];for(int j=0;j<beforeItems.get(k).size();j++){int item=beforeItems.get(k).get(j);if(group[item]==cur)//同一個組負責的項目,就加入項目-項目圖{itemDegree[k]++;itemEdges.get(item).add(k);}else{//不是同一個組負責的項目,就加入組-組圖{groupDegree[cur]++;groupEdges.get(group[item]).add(cur);}}}List<Integer> groupSort=toSort(groupDegree,groupEdges,groupId);//先對組——組圖進行拓撲排序if(groupSort.size()==0) return new int[0];List<Integer> ans=new ArrayList<>();for(int c:groupSort)//再對每個組,組內的項目進行拓撲排序{if(groupItems.get(c).size()==0) continue;List<Integer> in=toSort(itemDegree,itemEdges,groupItems.get(c));if(in.size()==0)return new int[0];ans.addAll(in);}return ans.stream().mapToInt(Integer::intValue).toArray();}public List<Integer> toSort(int[] degree,List<List<Integer>> edges,List<Integer> point){//拓撲排序代碼List<Integer> res=new ArrayList<>();Queue<Integer> queue=new LinkedList<>();for(Integer integer:point){if(degree[integer]==0)queue.offer(integer);}while (!queue.isEmpty()){int t=queue.poll();List<Integer> list=edges.get(t);for(int c:list){degree[c]--;if(degree[c]==0)queue.offer(c);}res.add(t);}return res.size()==point.size()?res:new ArrayList<>();}
}