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

636. Exclusive Time of Functions

时间:2017-12-16 15:55:23      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:read   line   开始   nat   while   efi   sorted by   blog   sorted   

Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions. 

Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function.

A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0. 

Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function‘s exclusive time. You should return the exclusive time of each function sorted by their function id.

Example 1:

Input:
n = 2
logs = 
["0:start:0",
 "1:start:2",
 "1:end:5",
 "0:end:6"]
Output:[3, 4]
Explanation:
Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. 
Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5.
Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. 
So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time.

 

 

struct Log
{
    int id;
    string s;
    int time;
    Log(int _id,string _s,int _time)
    {
        id = _id;
        s = _s;
        time = _time;     
    }
};

class Solution {
public:
    vector<int> exclusiveTime(int n, vector<string>& logs) {
        stack<Log> q;
        vector<int> res(n);
        for(auto log:logs)
        {
           vector<string> parsed = parse_log(log);
           int id =  stoll(parsed[0]);
           string s = parsed[1];
           int time = stoll(parsed[2]);
           Log curr_log(id,s,time);
           if(q.empty()||s=="start") q.push(curr_log);
           else
           {
               int curr_start_time = q.top().time;
               q.pop();
               int time_spent = time-curr_start_time+1;
               res[id] += time_spent;
                //下面这行的逻辑关系我刚开始没有想到,非常的优美。 
                if(!q.empty()) 
                    res[q.top().id]= res[q.top().id]-time_spent;   
           }
        }
        return res;   
    }
private:
vector<string> parse_log(string log)
{
     vector<string>res;
     string token;
     log +=":";
     stringstream is(log);
     while(getline(is,token,:))
        res.push_back(token);
     return res;                
}
    

};

 

636. Exclusive Time of Functions

标签:read   line   开始   nat   while   efi   sorted by   blog   sorted   

原文地址:http://www.cnblogs.com/jxr041100/p/8046525.html

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