关于#指针数组#的问题,如何解决?

朋友们,帮忙看个题啊
怎么计算每个队相应得分的呢?需要用指针数组来储存队名吗,队名和比赛记录需要分别用两个数组来储存吗?

img

img

实现步骤和详细代码实现如下:

  • 首先读入n,表示有n支队伍。
  • 然后读入n支队伍的名字,并将它们存入一个数组teams中。
  • 然后输入n(n-1)/2行数据,每行表示两支队伍之间的比赛结果。读入每一行数据时,分别计算出每支队伍的积分和净得分。
  • 最后使用qsort函数对teams数组按照积分、净得分、队名三个关键字进行排序。然后输出前n/2支队伍的名字即可。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_TEAM_NAME_LEN 50
#define MAX_TEAM_NUM 1000

typedef struct team_s
{
    char name[MAX_TEAM_NAME_LEN+1];
    int score;
    int net_score;
}team_t;

int compare(const void *a, const void *b)
{
    team_t *ta = (team_t *)a;
    team_t *tb = (team_t *)b;
    if (ta->score != tb->score)
        return tb->score - ta->score;
    if (ta->net_score != tb->net_score)
        return tb->net_score - ta->net_score;
    return strcmp(ta->name, tb->name);
}

int main()
{
    int n;
    scanf("%d", &n);

    team_t teams[MAX_TEAM_NUM];
    for (int i = 0; i < n; ++i)
        scanf("%s", teams[i].name);

    for (int i = 0; i < n; ++i)
    {
        for (int j = i + 1; j < n; ++j)
        {
            char name1[MAX_TEAM_NAME_LEN+1], name2[MAX_TEAM_NAME_LEN+1];
            int score1, score2;
            scanf("%s", name1);
            char c = getchar();
            while (c != '-') c = getchar();
            scanf("%s", name2);
            c = getchar();
            while (c != ':') c = getchar();
            scanf("%d-%d", &score1, &score2);

            int index1 = -1, index2 = -1;
            for (int k = 0; k < n; ++k)
            {
                if (strcmp(teams[k].name, name1) == 0)
                    index1 = k;
                if (strcmp(teams[k].name, name2) == 0)
                    index2 = k;
                if (index1 != -1 && index2 != -1)
                    break;
            }

            teams[index1].score += (score1 > score2 ? 3 : (score1 == score2 ? 1 : 0));
            teams[index2].score += (score2 > score1 ? 3 : (score1 == score2 ? 1 : 0));
            teams[index1].net_score += (score1 - score2);
            teams[index2].net_score += (score2 - score1);
        }
    }

    qsort(teams, n, sizeof(team_t), compare);

    for (int i = 0; i < n / 2; ++i)
        printf("%s\n", teams[i].name);

    return 0;
}

为了计算每个队相应的得分,可以使用指针数组来储存队名和相应的得分。具体来说,可以定义一个结构体,包含队名、得分和失分这三个字段,然后定义一个指向该结构体的指针数组。

比如,可以这样定义结构体和指针数组:

struct team {
  char name[51];
  int score;
  int lost;
};

struct team *teams[1001];

然后你可以分配内存,给每个指针分配一个结构体:

for (int i = 0; i < n; i++) {
  teams[i] = malloc(sizeof(struct team));
}

最后,你就可以使用指针数组来储存队名和得分了。比如,你可以这样赋值:

teams[i]->name = "team name";
teams[i]->score = 10;
teams[i]->lost = 5;

之后,你就可以根据题目要求,使用循环和分支语句来比较队伍的得分并排名了。