sicily 1063 Who's the boss

題目大意是給一串員工的ID,工資和身高(其中,ID和工資是唯一的),然後讓我們根據特定的ID,找出這個員工的老闆是誰以及下屬的個數。判斷員工A是員工B的老闆的標準是:A的身高大於等於B的身高,且在比B工資高的員工當中,A的工資是最低的。因此我們只需將員工按照工資排序,然後再根據身高來找老闆和下屬就可以了。但這道題還有一個需要注意的點,舉個例子來說:

111 1900  2000

222 2000 1900

333 1100 1000

444 1200 1100

按工資由低到高排序後是333,444,111,222. 此時,333和444都是111的下屬,儘管333和444身高,工資都小於222的,但222卻不是他們的上司。這放在現實中也很容易理解,比如說A和B是兩個不同部門的經理,即A和B地位相等,但是A的下屬卻不是B的下屬。

下面是我的源碼:

// Problem#: 1063
// Submission#: 3019936
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University

#include<iostream>
#include<vector>
#include<map>
#include<algorithm>

using namespace std;

struct Employee {
    int id;
    int salary;
    int height;
    Employee(int i, int s, int h) {
        id = i;
        salary = s;
        height = h;
    }
};

bool cmp(Employee e1, Employee e2) {
    return e1.salary < e2.salary;
}

bool operator<(Employee e1, Employee e2) {
    return e1.height <= e2.height;
}

bool operator>(Employee e1, Employee e2) {
    return e1.height >= e2.height;
}

int main() {
    int N;
    int q, m;
    int id, salary, height, query;
    vector<Employee> employees;
    map<int, int> temp;
    int queries[200];
    cin >> N;
    for (int n = 0; n < N; n++) {
        employees.clear();
        temp.clear();
        cin >> m >> q;
        for (int i = 0; i < m; i++) {
            cin >> id >> salary >> height;
            employees.push_back(Employee(id, salary, height));
        }
        for (int i = 0; i < q; i++) {
            cin >> query;
            queries[i] = query;
        }

        sort(employees.begin(), employees.end(), cmp);
        //用map 建立索引
        for (int i = 0; i < m; i++) {
            temp[employees[i].id] = i;
        }

        for (int i = 0; i < q; i++) {
            int index = temp[queries[i]];
            int subordinates = 0;
            // 找下屬的個數,當兩個員工無法比較時跳出循環
            for (int j = index - 1; j >=0; j--) {
                if (employees[j] < employees[index]) {
                   subordinates++;
                } else {
                    break;
                }
            }
            // 找上司
            int boss = 0;
            for (int j = index + 1; j < m; j++) {
                if (employees[j] > employees[index]) {
                    boss = employees[j].id;
                    break;
                }
            }
            cout << boss << " " << subordinates << endl;
        }
    }
    return 0;
}                                 



發佈了22 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章