富豪首富推理算法:C语言实现
以下是使用 C 语言编写的解决方案:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, m;
while (scanf("%d %d", &n, &m) == 2 && n != 0 && m != 0) {
int *netWorth = (int*) malloc((n + 1) * sizeof(int)); // 存储每个富豪的财富
int *count = (int*) malloc((n + 1) * sizeof(int)); // 计数
for (int i = 1; i <= n; i++) {
netWorth[i] = 0;
count[i] = 0;
}
for (int i = 0; i < m; i++) {
int a, b;
char c;
scanf("%d %c %d", &a, &c, &b);
if (c == '>') {
netWorth[a]++;
count[a]++;
count[b]--;
} else {
netWorth[b]++;
count[b]++;
count[a]--;
}
}
int maxNetWorth = -1;
int richestPerson = -1;
int found = 0;
for (int i = 1; i <= n; i++) {
if (count[i] == n - 1 && netWorth[i] > maxNetWorth) {
maxNetWorth = netWorth[i];
richestPerson = i;
found = 1;
}
}
if (found) {
printf("%d\n", richestPerson);
} else {
printf("no solution\n");
}
free(netWorth);
free(count);
}
return 0;
}
解释:
- 首先,使用
while循环读取多组输入,当输入的n和m同时为0时,结束输入。 - 在每组输入中,使用
malloc函数动态分配两个数组netWorth[]和count[],分别用于存储每个富豪的财富和计数。 - 使用
for循环初始化数组netWorth[]和count[],将其所有元素都设为0。 - 使用另一个
for循环,依次读取m行输入,每行包含一个整数a,一个字符c,和一个整数b,表示编号为a的富豪和编号为b的富豪的财富关系。 - 如果
c为>,则a富豪的财富增加1,同时a富豪的计数增加1,b富豪的计数减去1。 - 如果
c为<,则b富豪的财富增加1,同时b富豪的计数增加1,a富豪的计数减去1。 - 使用两个变量
maxNetWorth和richestPerson分别记录当前最大财富和最有可能是首富的富豪的编号,初始值设为-1。 - 使用另一个变量
found记录是否找到了首富,初始值设为0。 - 使用另一个
for循环遍历所有富豪,如果某个富豪的计数等于n - 1,并且财富大于maxNetWorth,则更新maxNetWorth和richestPerson的值,并将found设为1。 - 如果
found为1,则输出richestPerson,否则输出'no solution'。 - 最后,使用
free函数释放动态分配的内存。
原文地址: https://www.cveoy.top/t/topic/QVi 著作权归作者所有。请勿转载和采集!