【PAT B1032】挖掘机技术哪家强 (C语言)
代码实现
#include <stdio.h>
#define MAX 100001
int main(){
int n,score,sclID,k;
int i=0,max=0;
int scl[MAX]={0};
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d" "%d",&sclID,&score);
scl[sclID]+=score;
if(scl[sclID]>max){
max=scl[sclID];
k=sclID;
}
}
printf("%d %d\n",k,max);
return 0;
}错误记录
#include <stdio.h>
#define MAX 100000 //第一处
int main(){
int n,score,sclID,k;
int i,max=0;
int scl[MAX]={0};
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d" "%d",&sclID &score); //第二处
scl[sclID]+=score;
if(scl[sclID]>max){
max=scl[sclID];
k=i;
}
}
printf("d" "d",&k,&max);
return 0; //【第一次】 在PAT用gcc 6.5.0测试时,测试点3显示答案错误,应该是边界测试没过,但是用g++可以通过
//【第二处】 [Error] invalid operands to binary & (have 'int *' and 'int') 【没有加逗号】
尝试优化
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int score;
int flag;
}Scl;
int main() {
int n, sclID, maxID, max = 0, score; //定义数据个数,学校代码,最大分数代码,初始化最大值
Scl* S; //【第一处】
scanf("%d", &n);
S = (Scl*)malloc(n * sizeof(Scl)); //动态分配数组
int i = 0;
for (i; i < n; i++) {
scanf("%d" "%d", &sclID, &score);
if (S[sclID].flag == 1){
}
else {
S[sclID].score = 0;
S[sclID].flag = 1;
}
S[sclID].score += score;
if (S[sclID].score > max) {
max = S[sclID].score;
maxID = sclID;
}
}
free(S);
printf("%d %d\n", maxID, max);
return 0;
}优化失败
想通过动态分配减少内存使用,但是最后运行提示数组越界,因为动态分配的是连续的空间,而使用时输入数据不是连续的,从而导致错误。后面想用链表来做,但是感觉做出来过于复杂就放弃了。
C99 标准的c++可以定义变长数组...
scanf("%d",&n);
int a[n]= {0}; //【第一处】曾在动态分分配这样写
Scl.data = (Scl*)malloc(n * sizeof(Scl));
提示错误[Error] expected identifier or '(' before '.' token
改了很久,最后发现是将结构体类标识符误当做一个变量来使用。