第十三周算法分析与设计:Kill Process

来源:互联网 发布:手机屏幕跑出蜘蛛软件 编辑:程序博客网 时间:2024/06/11 05:59

问题描述:

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.
Note:
The given kill id is guaranteed to be one of the given PIDs.
n >= 1.

题目出自此处。


解法思路:
从父节点找子节点,一开始用map创建键值对容器,由于父节点和子节点基本是一对多的关系,而且为了防止插入重复的子节点,键和值分别使用intset<int>,分别存储父节点和其对应的子节点,一个父节点就成为了一棵树的根结点,它与子节点共同构成了一棵树。当完成存储后,利用层次遍历就可以把一棵树的节点全部取出来,这些节点就是要删除的“进程”了。

class Solution {public:    vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {        vector<int> result;        map<int,set<int>> children;        for(int i=0;i<pid.size();i++) {            children[ppid[i]].insert(pid[i]);        }        queue<int> q;        q.push(kill);        while(!q.empty()) {            int cur_node = q.front();            for(int child : children[cur_node]) {                q.push(child);            }            result.push_back(cur_node);            q.pop();        }                return result;    }};

原来C++迭代的时候也可以用“:”,方便方便~哦对了算法的时间复杂度大概为O(M+N)
(虐狗日上传一个小姐姐应景)
这里写图片描述

原创粉丝点击