c++ - 算法问题求解~
迷茫
迷茫 2017-04-17 11:39:47
0
1
577

A big coorperation has N employees. The employees form a strict hierarchy. Each emplyee has at most one direct boss. At the same time, he or she can be in charge of many other employees as a boss. Of course, if A is B's boss and B is C's boss, A is C's boss too. In this question we only care about two properties of each employee, name and age. We define that pair ('Bill', 39) -> 'Sarah' means 39-year-old Bill is Sarah's boss. Note that Bill is also an employee and may also has a boss. Given a list of information like this, you are supposed to build the hierarchy that supports one simple query: given an employee, ouput the name of the yongest age among all his or her bosses. If the employee has no boss, output his or her own name.

The first line of input contains 2 integers P (0 < P < 1000) and Q (0 < Q < 1000). P is the number of pairs and Q is the number of queries. Each line in the next P lines contains the boss' name, age (10 < age < 100) and the employee's name. Nobody is assigned as his or her own boss. The next Q lines each contains an employee name. If the employee name being queried is not found, string "I don't know who you are talking about." should be printed. All employee names only contain upper and lower case letters.

The output should be Q lines of results in cooresponding to each query.

Sample Input:

1 3
Bill 39 Sarah
Sarah
Bill
Jayce

Sample Output:

Bill
Bill
I don't know who you are talking about.

题目大概是上面这样。。

我用C++写了一个,但是跑不起来。

大致是这样。。

typedef struct person {
char *name;
int age;
person *boss;
} person;

然后在赋值的时候建立连个数组,一个是放关系的(p_array),一个是放想要查找的名字的(q_array)。

最后在输出的时候通过两个for循环,去找是否有想对应的p_array[i].name存不存在,如果存在就判断是否有boss,有就输出他的boss,没有就输出他自己的名字。如果p_array[i].name不存在,就输出不存在。

#include <stdio.h>

typedef struct person {
    char *name;
    int age;
    struct person *boss;
} person;

int main() {
    int P;
    printf("Input Number of Paris: ");
    scanf("%d", &P);

    int Q;
    printf("Input Number of Queries: ");
    scanf("%d", &Q);

    person p_array[P];
    char *boss_name;
    int boss_age;
    char *employee_name;
    for (int i = 0; i < P; i++) {
        printf("Input the Boss's name: ");
        scanf("%s", &boss_name);
        printf("Input the Boss's age: ");
        scanf("%d", &boss_age);
        printf("Input the Employee's name: ");
        scanf("%s", &employee_name);
        p_array[i].name = employee_name;
        p_array[i].boss->name = boss_name;
        p_array[i].boss->age = boss_age;
    }

    for (int j = 0; j < P; j++) {
        printf("%s\n", p_array[j].name);
    }
    return 0;
}
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

membalas semua(1)
伊谢尔伦

你的思路没有问题,跑不起来那就是你程序的问题了。
这是一个简单的树形自底向上遍历。

    typedef struct employee_t
    {
        string name;
        int age;
        employee_t* boss;
    } employee;

    map<string,employee*> employees;
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan