程序提交到oj上后一直runtime error
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
struct student
{
char g_num[12];
int p_num;
int score=0;
}stu[505];
int p[11];
bool comp(struct student a,struct student b)
{
if(a.score==b.score) return strcmp(a.g_num,b.g_num);
else return a.score>b.score;
}
int main()
{
int T;
cin>>T;
for(int i=0;i<T;i++)
{
int N,M,G,sum=0;
cin>>N>>M>>G;
for(int j=1;j<=M;j++)
{
int a;
cin>>a;
p[j]=a;
}
for(int j=0;j<N;j++)
{
stu[j].score=0;
scanf("%s %d",stu[j].g_num,&stu[j].p_num);
for(int k=0;k<stu[j].p_num;k++)
{
int temp;
cin>>temp;
stu[j].score+=p[temp];
}
if(stu[j].score>=G) sum++;
}
sort(stu,stu+N,comp);
printf("case #%d:\n",i);
cout<<sum<<endl;
for(int j=0;j<sum;j++)
{
printf("%s %d\n",stu[j].g_num,stu[j].score);
}
}
}
你代码运行时超时了,检查循环嵌套是不是太多
你的comp函数写得不对:
bool comp(struct student a,struct student b)
{
if(a.score==b.score) return strcmp(a.g_num,b.g_num);
else return a.score>b.score;
}
假设:
a.score = 1;
a.g_num = "12";
b.score = 1;
b.g_num = "23";
strcmp("12","23") = -1, strcmp("23","12")=1, 1和-1都是true。所以会出现:
comp(a,b) == true 同时 comp(b, a) == true, 矛盾。std::sort检查到这种情况,就认为你的comp函数是错误的,就抛出RunTime Error。
修改方法:
bool comp(struct student a, struct student b)
{
if (a.score == b.score)
return strcmp(a.g_num, b.g_num) < 0;
else
return a.score > b.score;
}