题解 | #旅行Ⅰ#

旅行Ⅰ

http://www.nowcoder.com/practice/ecc6e261da68412caad810669b1e891f

class Solution {
public:
    struct status {
        int city; // 从0到n-1
        int cost; // 花费
        bool operator < (const status& a) const { // 为优先队列制定规则
            if (cost != a.cost) // 先看消费,选消费低的
                return cost > a.cost;
            else // 消费一样选城市编号小的
                return city > a.city;
        }
    };
    int Travel(int N, int V, vector<int>& A, vector<Point>& list) {
        // 用来存储一个城市到其他城市的图,用于拓扑排序
        unordered_map<int,unordered_set<int>> graph; 
        vector<int> inDgrees(N, 0); // 存储每个城市结点的入度,没有强迫症要求的入度为0
        priority_queue<status> q;
        for (auto& point: list) {
            graph[point.x-1].insert(point.y-1);
            inDgrees[point.y-1]++;
        }
        for (int i = 0; i < N; i++) { // 创建完图后,把入度为0的结点放入优先队列
            if (inDgrees[i] == 0) {
                q.push({i,A[i]});
            }
        }
        int costSum = 0, cnt = 0;
        while (!q.empty()) {
            status top = q.top();
            q.pop();
            costSum += top.cost;
            if (costSum > V) // 本次消费会炸,只能返回上次的城市数cnt
                break;
            cnt++;
            for (auto i: graph[top.city]) { // 讲当前弹出的城市与其他城市的连接断开,即其他城市入度-1
                inDgrees[i]--;
                if (inDgrees[i] == 0)
                    q.push({i,A[i]});
            }
        }
        return cnt;
    }
};
全部评论

相关推荐

06-25 16:00
武汉大学 Java
工科研究生底薪工资就开3k啊??
机械打工仔:写文章提成的岗位工资低,你怪工科?
点赞 评论 收藏
分享
06-26 19:47
中南大学 Java
悲,毕业了!这是个坏事儿啊!
爱睡觉的冰箱哥:《这是个好事啊》---峰哥浪走天涯
毕业后不工作的日子里我在...
点赞 评论 收藏
分享
小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务