码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Kill Process

时间:2017-05-16 14:55:33      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:turn   push   vector   UI   color   return   优先   desc   its   

582. Kill Process

 

Given n processes, each process has a unique PID (process id) and its PPID (parent process id).

Each process only has one parent process, but may have one or more children processes. This is just like a tree structure. Only one process has PPID that is 0, which means this process has no parent process. All the PIDs will be distinct positive integers.

We use two list of integers to represent a list of processes, where the first list contains PID for each process and the second list contains the corresponding PPID.

Now given the two lists, and a PID representing a process you want to kill, return a list of PIDs of processes that will be killed in the end. You should assume that when a process is killed, all its children processes will be killed. No order is required for the final answer.

Example 1:

Input: 
pid =  [1, 3, 10, 5]
ppid = [3, 0, 5, 3]
kill = 5
Output: [5,10]
Explanation: 
           3
         /           1     5
             /
            10
Kill 5 will also kill 10.

思路:这里使用广度优先搜素就可以了,无需构建树。
 1 vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) 
 2 {
 3     vector<int>res,q1, q2;
 4     map<int, vector<int>>m;
 5     if (pid.size() == 0 || ppid.size() == 0)
 6         return res;
 7     for (int i = 0; i < ppid.size(); i++)
 8         m[ppid[i]].push_back(pid[i]);
 9     q1.push_back(kill);
10     while (q1.size())
11     {
12         for (int i = 0; i < q1.size(); i++)
13         {
14             res.push_back(q1[i]);
15             for (int j = 0; j < m[q1[i]].size(); j++)
16                 q2.push_back(m[q1[i]][j]);
17         }
18         swap(q1, q2);
19         q2.clear();
20     }
21     return res;
22 }

 

LeetCode:Kill Process

标签:turn   push   vector   UI   color   return   优先   desc   its   

原文地址:http://www.cnblogs.com/maclearning/p/6860917.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!