题目逻辑比较清晰,但是要解决超时问题。
方法:人的名字最多有26*26*26*10个,所以就构建一个这么大的数组,用于存放每个人的信息
这样效率就高了,还要注意,c++也得用scanf输入printf输出,要不然最后一个还是超时。
代码如下:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
using namespace std;
//ifstream in("1039.txt");
//#define cin in
struct student
{
char name[5];
vector<int> course;
};
struct student a[26*26*26*10];
bool flag[26*26*26*10] = {false};
int str2int(char * name)
{
int temp = 0;
for(int i = 0;i<4;i++)
if(i < 3)
temp = temp*26 + name[i]-'A';
else
temp = temp*10 + name[i] - '0';
return temp;
}
int main()
{
int N,K;
// cin >> N >> K;
scanf("%d %d",&N,&K);
int i = 0;
for(;i < K;i++)
{
int index,num;
// cin >> index >> num;
scanf("%d %d",&index,&num);
for(int j = 0;j<num;j++)
{
char str[5];
scanf("%s",str);
int temp = str2int(str);
if(!flag[temp])
{
strcpy(a[temp].name,str);
// a[temp].name = str;
flag[temp] = true;
}
a[temp].course.push_back(index);
}
}
for(i = 0;i<N;i++)
{
char name[5];
scanf("%s",name);
printf("%s ",name);
int tmp = str2int(name);
if(!flag[tmp])
cout << 0 << endl;
else
{
sort(a[tmp].course.begin(),a[tmp].course.end());
cout << a[tmp].course.size();
for(int j = 0;j<a[tmp].course.size();j++)
cout << " " << a[tmp].course[j];
cout << endl;
}
}
return 0;
}

本文探讨了一种通过构建大型数组来提高效率的方法,解决算法超时问题,并强调了使用C++的正确输入输出方式。文章详细介绍了从输入数据到处理和输出结果的全过程。
2170

被折叠的 条评论
为什么被折叠?



