4.19华为_机试算法share

第一题:服务器能耗统计

#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1000010;
int n, res, q[N];

int main()
{
    cin >> n;
    int MAX = 0, MIN = N;
    for(int i = 0; i < n; i++){
        int a, b;
        cin >> a >> b;
        q[a]++, q[b + 1]--;
        MAX = max(MAX, b);
        MIN = min(MIN, a);
    }
    for (int i = MIN; i <= MAX; i ++ ){
        q[i] += q[i - 1];
        if(!q[i]) res += 1;
        else if(q[i] == 1) res += 3;
        else res+= 4;
    }
    cout << res << endl;
    return 0;
}

第二题:树上逃离

#include <iostream>
#include <queue>
#include <cstring>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;
int n, m, k, p;
int b[N], h[N], e[N], ne[N], idx;
string path[N], res[N];

void add(int a, int b){
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void bfs(){
    queue<int> q;
    q.push(0);
    path[0] = "0";
    while (!q.empty()){
        int x = q.front();
        q.pop();
        int idx = 0; //用来记录i节点的子节点是否到达叶子节点,如果是的话将结果集res从小到大排序后输出结果
        for(int i = h[x]; i != -1; i = ne[i]){
            int j = e[i];
            if(!b[j]){
                q.push(j);
                path[j] = (path[x] + "->" + to_string(j));
                if(h[j] == -1) {
                    idx = 1;
                    res[p++] = path[j];
                }
            }
        }
        if(idx){ 
            sort(res, res + p);
            cout << res[0] << endl;
            return;
        }   
    }
    cout << "NULL" << endl;
}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for(int i = 0; i < m; i++){
        int a, b;
        cin >> a >> b;
        add(a, b);
    }
    cin >> k;
    for(int i = 0; i < k; i++){
        int t;
        cin >> t;
        b[t] = 1;
    }
    bfs();
    return 0;
}

全部评论
第二题的tmp数组那里不对哎
点赞 回复 分享
发布于 2023-04-25 18:57 江苏

相关推荐

03-11 14:28
浙江大学 设计
牛客小黄鱼:代入一下,独居女生会觉得有点可怕
点赞 评论 收藏
分享
评论
2
6
分享

创作者周榜

更多
牛客网
牛客企业服务