Codeup Problem A: 任务调度【优先序列+重载】

原题地址

(是codeup新家哦!速度比较快~)
http://codeup.hustoj.com/problem.php?cid=100000601&pid=0

解题思路

用个priority_queue,结构体内重载运算符,然后根据题目要求每次给出top()

我用了一个map来存储每个task对应的优先级~

注意事项

1.一开始还想复杂了,以为输入的先序任务是不按照顺序的,但其实是按照顺序的~所以默认第一个输进来的是第一个执行,用map判断即可。

然后因为是按照执行的顺序输入的,所以后输入的这个先序任务一定优先级比上一个先序任务多1,所以每次循环的时候要记得存储一下现在的先序任务~

2.队列的这个top()函数,使用前一定要先判断是否队列非空!!不然会出错滴~

参考代码

#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
typedef double db;
typedef long long LL;
typedef vector<int> VI;
const int inf = 2e9;
const LL INF = 8e18;
const int maxn = 5e5 + 5;
struct Task{
 int level;
 string name;
 friend bool operator < (Task a, Task b) {
  if (a.level != b.level) return a.level > b.level;
  return a.name > b.name;
 }
};
int main() {
 int n;
 cin >> n;
 string s, f, l, pre;
 Task now;
 unordered_map<string, int> smp;
 priority_queue<Task> p;
 int firstlevel = 0;
 for (int i = 0; i < n; i++) {
  cin >> s;
  int pos = s.find('(');
  f = s.substr(0, pos);  //f表示先序任务 
  s.erase(0, pos + 1);
  now.name = f;
  if (!smp[f]) {
   now.level = 0;
   smp[f] = 0;
  } else now.level = smp[pre] + 1;
  p.push(now);
  while (1) {
   pos = s.find(',');
   if (pos != -1) {
    l = s.substr(0, pos);  //l表示后序任务 
    smp[l] = smp[f] + 1;
    s.erase(0, pos + 1);
   }
   else {
    pos = s.find(')');
    l = s.substr(0, pos);
    if (l != "NULL") 
     smp[l] = smp[f] + 1;
    break;
   }
  }
  pre = f;  //存储一下现在的先序任务 
 }
 while (!p.empty()) {  //记得判断啊!! 
  cout << p.top().name;
  p.pop();
  if (p.size() != 0) cout << ' ';
 }
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值