首页 > 试题广场 >

Course List for Student (25)

[编程题]Course List for Student (25)
  • 热度指数:1887 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
Zhejiang University has 40000 students and provides 2500 courses. Now given the student name lists of all the courses, you are supposed to output the registered course list for each student who comes for a query.

输入描述:
Each input file contains one test case.  For each case, the first line contains 2 positive integers: N (<=40000), the number of students who look for their course lists, and K (<=2500), the total number of courses.  Then the student name lists are given for the courses (numbered from 1 to K) in the following format: for each course i, first the course index i and the number of registered students Ni (<= 200) are given in a line.  Then in the next line, Ni student names are given.  A student name consists of 3 capital English letters plus a one-digit number.  Finally the last line contains the N names of students who come for a query.  All the names and numbers in a line are separated by a space.


输出描述:
For each test case, print your results in N lines.  Each line corresponds to one student, in the following format:  first print the student's name, then the total number of registered courses of that student, and finally the indices of the courses in increasing order.  The query results must be printed in the same order as input.  All the data in a line must be separated by a space, with no extra space at the end of the line.
示例1

输入

11 5<br/>4 7<br/>BOB5 DON2 FRA8 JAY9 KAT3 LOR6 ZOE1<br/>1 4<br/>ANN0 BOB5 JAY9 LOR6<br/>2 7<br/>ANN0 BOB5 FRA8 JAY9 JOE4 KAT3 LOR6<br/>3 1<br/>BOB5<br/>5 9<br/>AMY7 ANN0 BOB5 DON2 FRA8 JAY9 KAT3 LOR6 ZOE1<br/>ZOE1 ANN0 BOB5 JOE4 JAY9 FRA8 DON2 AMY7 KAT3 LOR6 NON9

输出

ZOE1 2 4 5<br/>ANN0 3 1 2 5<br/>BOB5 5 1 2 3 4 5<br/>JOE4 1 2<br/>JAY9 4 1 2 4 5<br/>FRA8 3 2 4 5<br/>DON2 2 4 5<br/>AMY7 1 5<br/>KAT3 3 2 4 5<br/>LOR6 4 1 2 4 5<br/>NON9 0
PAT A1039 57ms 
刚开始自然想到map映射,但是最后一例超时。。
后来利用空间换时间+hash表
降低排序规模
最后一例都超时
最后放弃cin cout改为 scanf 和printf。。奇迹般只有57ms了
#include<string>
#include<map>
#include<vector>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
using namespace std;
bool present[175761];
vector<int>* RgList[175761];
char namei[5];
struct info {
 int coursId;
 vector<int> nameList;
};
info* infoList[2510];
bool cmp(info* A, info* B) {
 return A->coursId < B->coursId;
}
int cHash(char* str) {
 return (str[0] - 'A') * 6760 + (str[1] - 'A') * 260 + (str[2] - 'A') * 10 + (str[3] - '0');
}
int main() {
 int n, k;
 //map<string, vector<int>*>RgList;
 scanf("%d%d", &n, &k);
 memset(present, 0, sizeof(present));
 memset(RgList, 0, sizeof(RgList));
 for (int i = 0; i < k; i++) {
  int corsId, sNum;
  scanf("%d%d", &corsId, &sNum);
  info* infoi = new info;
  infoi->coursId = corsId;
  for (int j = 0; j < sNum; j++) {
   scanf("%s", namei);
   int nameHash = cHash(namei);
   infoi->nameList.push_back(nameHash);
  }
  infoList[i] = infoi;
 }
 sort(infoList, infoList + k, cmp);
 for (int i = 0; i < k; i++) {
  int corsId= infoList[i]->coursId, sNum=infoList[i]->nameList.size();
  for (int j = 0; j < sNum; j++) {
   int nameHash= infoList[i]->nameList[j];
   if (!present[nameHash]) {
    vector<int>* listi = new vector<int>;
    listi->push_back(corsId);
    RgList[nameHash] = listi;
    present[nameHash] = true;
   }
   else RgList[nameHash]->push_back(corsId);
  }
 }
 for (int i = 0; i < n; i++) {
  scanf("%s", namei);
  int nameHash = cHash(namei);
  if(!present[nameHash]) {
   vector<int>* listi = new vector<int>;
   RgList[nameHash] = listi;
  }
  printf("%s %d" ,namei,RgList[nameHash]->size());
  for (int j = 0; j < RgList[nameHash]->size(); j++) {
   printf(" %d", RgList[nameHash]->at(j));
  }
  printf("\n");
 }
 return 0;
} 

发表于 2018-01-26 17:17:14 回复(0)
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
const int maxn=200000;
int n,k;
vector<int>v[maxn],course[2505];
char str[10];
int hashcode(char *s){
    int ret=0;
    for(int i=0;i<3;i++){
        ret=ret*27+s[i]-'A';
    }
    ret=ret*10+s[3]-'0';
    return ret;
}
void solve(){
    scanf("%s",str);
    int x=hashcode(str);
    printf("%s",str);
    printf(" %d",v[x].size());
    for(int i=0;i<v[x].size();i++){
        printf(" %d",v[x][i]);
    }
    printf("\n");
}
int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    scanf("%d%d",&n,&k);
    int id,m;
    for(int i=0;i<k;i++){
        scanf("%d%d",&id,&m);
        while(m--){
            scanf("%s",str);
            int x=hashcode(str);
            course[id].push_back(x);
        }
    }
    for(int i=1;i<=k;i++){
        for(int j=0;j<course[i].size();j++){
            v[course[i][j]].push_back(i);
        }
    }
    for(int i=0;i<n;i++){
        solve();
    }
    return 0;
}
字符串映射到一个数组,用个course数组存放所有课程,可以省掉排序(PS:空间换时间)

#include<cstdio>
#include<algorithm>
#include<set>
#include<cstring>
#include<iterator>
using namespace std;
const int maxn=200000;
int n,k;
set<int>v[maxn];
char str[10];
int hashcode(char *s){
    int ret=0;
    for(int i=0;i<3;i++){
        ret=ret*27+s[i]-'A';
    }
    ret=ret*10+s[3]-'0';
    return ret;
}
void solve(){
    scanf("%s",str);
    int x=hashcode(str);
    printf("%s",str);
    printf(" %d",v[x].size());
    for(set<int>::iterator it=v[x].begin();it!=v[x].end();it++){
        printf(" %d",*it);
    }
    printf("\n");
}
int main(){
    //freopen("in.txt","r",stdin);
    scanf("%d%d",&n,&k);
    int id,m;
    for(int i=0;i<k;i++){
        scanf("%d%d",&id,&m);
        while(m--){
            scanf("%s",str);
            int x=hashcode(str);
            v[x].insert(id);
        }
    }
    for(int i=0;i<n;i++){
        solve();
    }
    return 0;
}
set版本,在pat上是190ms水过(PS:时间限制200ms)
编辑于 2016-08-03 23:18:54 回复(0)
用map是可以的,只不过把学生的名字作为key,把每个学生对应的课程都放到vector里作为map的value就可以了。map<string,vector<int>>这样不会超时的。
#include<stdio.h>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;

map<string, vector<int>> m;

int main()
{
    int N, K;
    scanf("%d%d", &N, &K);
    for (int i = 0; i < K; i++)
    {
        int course, M;
        scanf("%d%d", &course, &M);
        for (int j = 0; j < M; j++)
        {
            char student[5];
            scanf("%s", student);
            if (m.count(student) == 0)
            {
                vector<int> list;
                list.push_back(course);
                m[student] = list;
            }
            else
            {
                m[student].push_back(course);
            }
        }
    }
    for (int i = 0; i < N; i++)
    {
        char student[5];
        scanf("%s", student);
        printf("%s %d", student, m[student].size());
        sort(m[student].begin(), m[student].end());
        for (int j = 0; j < m[student].size(); j++)
        {
            printf(" %d", m[student][j]);
        }
        printf("\n");
    }
    return 0;
}


发表于 2019-08-17 23:00:52 回复(0)
思路:C++ 里面散列表最常用的是map了定义一个   map<string, vector<int> >基本就解决了。
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
using namespace std;

#ifndef debug
ifstream ifile("case.txt");
#define cin ifile
#endif


int main()
{
    int n, course;
    cin >> n >> course;
    map<string, vector<int> > mp;
    int classNum, stuNum;
    string name;
    for (int i = 0; i < course; i++)
    {
        cin >> classNum >> stuNum;
        for (int j = 0; j < stuNum; j++)
        {
            cin >> name;
            mp[name].push_back(classNum);
        }
    }
    for (int i = 0; i < n; i++)
    {
        cin >> name;
        cout << name << " ";
        cout << mp[name].size();
        sort(mp[name].begin(), mp[name].end());
        for (int j = 0; j < mp[name].size(); j++)
        {
            cout << " " << mp[name][j];
        }
        cout << endl;
    }
    system("pause");
}

发表于 2018-08-30 07:03:16 回复(0)
n, k = map(int, input().strip().split())
d = {}
for i in range(k):
    t = list(input().split())
    ind = int(t[0])
    for x in t[2:]:
        if x not in d:
            d[x] = []
        d[x].append(ind)
q = input().strip().split()
for x in q:
    if x not in d:
        print(x, 0)
    else:
        print(x, len(d[x]), ' '.join(map(str,sorted(d[x]))))

发表于 2018-05-03 14:39:16 回复(0)
啥头像
用了一个死办法

总体思路:
        1.用这种结构vector<set<int> >存储每个学生所选的课程,set自动排序,就是费时

代码如下:
#include <iostream>
#include <set>
#include <vector>
#include <map>

using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    // 读入数据
    int N, K; cin >> N >> K;
    int courseID, nums, id; string name;
    map<string, int> link; vector<set<int> > data;
    for(int i=0; i<K; i++) {
        cin >> courseID >> nums;
        while(nums--) {
            cin >> name;
            if(link.count(name)) {
                id = link[name];
                data[id].insert(courseID);
            } else {
                id = data.size();
                link[name] = id; set<int> tempSet;
                data.push_back(tempSet);
                data[id].insert(courseID);
            }
        }
    }

    // 处理请求
    set<int>::iterator iter;
    while(N--) {
        cin >> name;
        if(link.count(name)) {
            id = link[name]; nums = data[id].size();
            cout << name << " " << nums; iter = data[id].begin();
            for(; iter!=data[id].end(); iter++) {
                cout << " " << *iter;
            }
        } else {
            cout << name << " 0";
        }
        cout << endl;
    }
    return 0;
} 


发表于 2015-12-23 19:37:39 回复(0)
#include<bits/stdc++.h>
using namespace std;

const int Max=26*26*26*10+1;

string name;
vector<int> course[Max];

int getId(string name) {
	int id=0,l=name.size();
	for(int i=0; i<l-1; i++) {
		id=id*26+(name[i]-'A');
	}
	id=id*10+(name[l-1]-'0');
	return id;
}

int main() {
    ios::sync_with_stdio(0);
	int n,m;
	cin>>n>>m;
	for(int i=1; i<=m; i++) {
		int id,x;
		cin>>id>>x;
		for(int j=1; j<=x; j++) {
			cin>>name;
			int a=getId(name);
			course[a].emplace_back(id);
		}
	}
	for(int i=1; i<=n; i++) {
		cin>>name;
		int a=getId(name);
		int h=course[a].size();
		cout<<name<<" "<<h;
		sort(course[a].begin(),course[a].end());
		for(int j=0; j<h; j++) {
			cout<<" "<<course[a][j];
		}
		cout<<endl;
	}
	return 0;
}

发表于 2022-11-18 15:10:24 回复(1)
原题的“increasing order”是数字顺序不是字典序 所以不能用string的map[呲牙]
#include<iostream>
#include<string>
#include<map>
#include<set>

using namespace std;

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);

    // increasing order 是数字顺序不是字典序 所以不能用string的map[呲牙]
    map<string, set<int> > m;

    // N (≤40,000), the number of students who look for their course lists
    // K (≤2,500), the total number of courses.
    int N, K;
    cin >> N >> K;

    for (int i = 0; i < K; ++i) {
        int course;
        int stu_num;
        cin >> course >> stu_num;
        for (int j = 0; j < stu_num; ++j) {
            string stu_name;
            cin >> stu_name;
            m[stu_name].insert(course);
        }
    }

    string name;
    while(N--) {
        cin >> name;
        cout << name << ' ' << m[name].size();
        for (set<int>::iterator x = m[name].begin(); x != m[name].end(); x++) {
            cout << ' ' << *x;
        }
        cout << endl;
    }

    return 0;
}


发表于 2020-09-21 20:09:52 回复(0)
//参考了一下别人的想法,用map<string,vector<int> > .
#include<iostream>
(720)#include<vector>
#include<algorithm>
(831)#include<map>
using namespace std;
int main() {
	int n, k;
	cin >> n >> k;
	map<string, vector<int> >mymap;
	for (int i = 1; i <=k; i++) {
		int course, num;
		cin >> course >> num;
		for (int i = 0; i < num; i++) {
			string name;
			cin >> name;
			mymap[name].push_back(course);
		}
	}
	for (int i = 0; i < n; i++) {
		string name;
		cin >> name;
		printf("%s ", name.c_str());
		vector<int>tmp = mymap[name];
		printf("%d ", tmp.size());
		sort(tmp.begin(), tmp.end());
		for (int j = 0; j < tmp.size(); j++) {
			if (j) { printf(" "); }
			printf("%d", tmp[j]);
		}
		printf("\n");
	}
}

发表于 2020-03-28 12:08:19 回复(0)
pta上有一个用例的一节课程没有学生,也就不会输出下一排,一定要加个判断;
牛客上课程和学生是在一排的
a = list(map(int,input().split()))
d = {}
for i in range(a[1]):
    b = list(map(int,input().split()))
    if b[1] == 0:
        continue
    for j in input().split():
        try:
            d[j].append(b[0])
        except:
            d[j] = [b[0]]
    
for i in input().split():
    try:
        print(i,len(d[i]),' '.join(map(str,sorted(d[i]))))
    except:
        print(i,0)
pta上最后一个用例极可能超时(因为要加那些通过其它用例的判断部分,没错说的就是你用例1);

发表于 2020-02-22 15:39:10 回复(0)
简单的unordered_map套priority_queue
#include<iostream>
#include<queue>
#include<unordered_map>

using namespace std;
unordered_map<string,priority_queue<int,vector<int>,greater<int> > > stukeylist;

int num_stu,num_cour,ind,ind_stu;
string stu;

int main() {
	cin >> num_stu >> num_cour;
	for(int i = 0; i < num_cour ; ++i) {
		cin >> ind >> ind_stu;
		for(int j = 0; j < ind_stu; ++j) {
			cin >> stu;
			stukeylist[stu].push(ind);
		}
	}
	for(int i = 0; i < num_stu; ++i) {
		cin >> stu;
		cout << stu << " " << stukeylist[stu].size() << " ";
		if(stukeylist[stu].empty()) {
			cout << "\n";
		} else {
			while(!stukeylist[stu].empty()) {
				cout << stukeylist[stu].top() ;
				stukeylist[stu].pop();
				cout << ((stukeylist[stu].empty())?"\n":" ");
			}
		}
	}

}

发表于 2020-01-29 15:33:58 回复(0)

刚开始思路是把用map保存课程和学生,然后学生都添加到课程里面,然后根据学生姓名然后遍历每个课程,存在则证明该学生选了该课程,但是最后一个点一直过不去,超时,最后退而求其次把map改成课程加入学生的方法,就好了

#include<iostream>
#include<stdlib.h>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
map<string,vector<int>> course;

int main() {
    int n = 0, k = 0, index = 0, m = 0;//n请求查询的人数,k课程数
    char str[5];
    scanf("%d%d",&n,&k);
    for (int i = 1; i <= k; i++) {//把选了该课程的学生压入此课程的数组中
        scanf("%d%d",&index,&m);
        for (int j = 0; j < m; j++) {
            scanf("%s",str);
            if (course.count(str) != 0) course[str].push_back(index);
            else { 
                vector<int> tem;
                tem.push_back(index);
                course.insert(pair < string, vector<int>>(str,tem));
            }
        }
    }
    for (int i = 0; i < n; i++) {
        scanf("%s",str);
        printf("%s ",str);
        cout << course[str].size();
        sort(course[str].begin(), course[str].end());
        for (vector<int>::iterator it = course[str].begin(); it != course[str].end(); it++)cout <<" "<< *it;
        printf("\n");
    }
    system("pause");
    return 0;
}
编辑于 2019-10-13 22:59:42 回复(0)
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>

using namespace std; 

struct stu{
    int id;
    vector<int>Course;
    int num;
    stu(){
        num=0;
    }
};

int P(string a){
    int n = 0;
    for(int i=0; i<3; i++)
        n =  n*26+a[i]-'A';
    n = n*10 + a[3] - '0';
    return n;
}

int main(void){
    int n,k,i;
    cin>>n>>k;
    vector<stu>A;
    int Max=26*26*26*10;
    A.resize(Max);
    for(i=0; i<k; i++){
        int j, nj;
        cin>>j>>nj;
        for(int m=0; m<nj; m++){
            string temp1;
            cin>>temp1;
            int temp2 = P(temp1);
            A[temp2].Course.push_back(j);
            A[temp2].num++;
        }
    }
    for(i=0; i<n; i++){
        string S;
        cin>>S;
        int t = P(S);
        sort(A[t].Course.begin(),A[t].Course.end());
        cout<<S<<" "<<A[t].num;
        if(A[t].num > 0) {
            cout<<" ";
            for(int j=0; j<A[t].num;j++){
                cout<<A[t].Course[j];
                if(j != A[t].num-1) cout<<" ";
            }
        }
        if(i != n-1)cout<<endl;
    }
    return 0;
}

发表于 2019-06-12 22:46:00 回复(0)
#include <iostream>                //不用hash而用map或者set会超时 #include <algorithm> #include <vector> using namespace std; const int maxn=26*26*26*10+1;      //姓名散列的数字上界 vector<int> student[maxn];         //每个学生选的课的编号 int getid(char s[]){               //将姓名字符串散列成数字  int id=0;  for(int i=0;i<3;i++)   id=id*26+(s[i]-'A');  id=id*10+(s[3]-'0');  return id; } int main(){  char name[5];  int n,k;  scanf("%d%d",&n,&k);  for(int i=0;i<k;i++){   int course,num;   scanf("%d%d",&course,&num);   for(int j=0;j<num;j++){    scanf("%s",name);    int id=getid(name);    student[id].push_back(course);   //将该课程加入该学生的选课列表   }  }  for(int i=0;i<n;i++){   scanf("%s",name);   int id=getid(name);   sort(student[id].begin(),student[id].end ()); //将该学生选的课升序排列   printf("%s %d",name,student[id].size());   for(int j=0;j<student[id].size();j++)    printf(" %d",student[id][j]);   printf("\n");  }  return 0; }
//方法二:用地图在PAT最后一例会超时 #include <map> #include <vector> #include <string> #include <algorithm> #include <iostream> using namespace std;
int main(){  int n,k,ni,ki,num;  map<string,vector<int> >student;  string name;  cin>>n>>k;  for(int i=0;i<k;i++){   cin>>ki>>ni;   for(int j=0;j<ni;j++){    cin>>name;    student[name].push_back(ki);   }  }  for(int i=0;i<n;i++){   cin>>name;   if(student.count(name)>0){    cout<<name<<" "<<student[name].size();    sort(student[name].begin(),student[name].end());    for(int j=0;j<student[name].size();j++)     cout<<" "<<student[name][j];    cout<<endl;   }   else    cout<<name<<" "<<0<<endl;  }  return 0; }

编辑于 2019-01-03 16:39:22 回复(1)

n,k=map(int,input().split())
out = {}
for i in range(0,k):
    tem = list(input().split())
    for i in tem[2:]:
        if i not in out:
            out[i] = []
        out[i].append(tem[0])
stu = list(input().split())
for i in stu:
    if i not in out:
        print(i+" 0")
    else:
        print(i+" "+str(len(out[i]))+" "+' '.join(map(str,sorted(map(int,out[i])))))
要注意的是。。。这道题输入的课程id,查询人数和students在一行
编辑于 2018-12-07 11:09:04 回复(0)
纯stl实现,耗时70ms
#include <bits/stdc++.h>
using namespace std;

int main() {     int n, k;     cin >> n >> k;          unordered_map<string, vector<int>> map;     for(int i = 0; i < k; ++i) {         int index, stus;         cin >> index >> stus;         string name;         for(int j = 0; j < stus; ++j) {             cin >> name;             map[name].push_back(index);         }     }          string query;     auto q = [&](auto& s) {         if(map.find(s) != map.end()) {             cout << s << " " << map[s].size() << (map[s].size() == 0 ? '\n' : ' ');             sort(map[s].begin(), map[s].end());             for(int i = 0; i < map[s].size(); ++i)                 cout << map[s][i] << (map[s].size() == i+1 ? '\n' : ' ');         }         else{             cout << s << " " << 0 << '\n';         }     };          for(int i = 0; i < n; ++i) {         cin >> query;         q(query);     }     


编辑于 2018-11-15 16:30:17 回复(0)
N,K=map(int,input().split())
student={}
for i in range(K):
    t=list(input().split())
    for i in range(2,len(t)):
        if t[i] not in student:
            student[t[i]]=[]
        student[t[i]].append(int(t[0]))
query=list(input().split())
for e in query:
    tmp=sorted(student[e]) if e in student else []
    print(e,len(tmp),' '.join(map(str,tmp)))

发表于 2018-09-05 21:42:14 回复(0)
很奇怪  现在的代码是64ms,如果在主函数里面加上这句话(ios::sync_with_stdio(false);)反而增加到了84ms  希望有大佬能解惑  十分感谢(^~^) 
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
map<string,vector<int> > student;
int main() {
    int courseNumber,personNumber;
    cin>>personNumber>>courseNumber;
    for(int i=1; i<=courseNumber; ++i) {
        int courseIndex,number;
        cin>>courseIndex>>number;
        for(int j=1; j<=number; ++j) {
            string name;
            cin>>name;
            student[name].push_back(courseIndex);
        }
    }
    for(int i=1; i<=personNumber; ++i) {
        string query;
        cin>>query;
        if(i!=1) cout<<endl;
        cout<<query<<" "<<student[query].size();
        sort(student[query].begin(),student[query].end());
        for(auto vec_it=student[query].begin(); vec_it!=student[query].end(); vec_it++) {
            cout<<" "<<*vec_it;
        }
    }
    return 0;
}
发表于 2018-08-11 17:06:00 回复(0)
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;

const int maxn = 26 * 26 * 26 * 10;

int getId(char name[]){
    int id = 0;
    for(int i = 0;i < 3;i++){
        id = id * 26 + name[i] - 'A';
    }
    id = id * 10 + name[3] - '0';
    return id;
}

int main(){
    int n, k;
    vector<int> student[maxn];
    scanf("%d%d", &n, &k);
    int courseid, stuNum;
    char name[5];
    for(int i = 0;i < k;i++){
        scanf("%d%d", &courseid, &stuNum);
        for(int j = 0;j < stuNum;j++){
            scanf("%s", name);
            int id = getId(name);
            student[id].push_back(courseid);
        }
    }
    for(int i = 0;i < n;i++){
        scanf("%s", name);
        int id = getId(name);
        sort(student[id].begin(), student[id].end());
        printf("%s %d", name, student[id].size());
        for(int j = 0;j < student[id].size();j++){
            printf(" %d", student[id][j]);
        }
        printf("\n");
    }

    return 0;
}
发表于 2018-03-11 10:36:33 回复(0)

问题信息

难度:
22条回答 7816浏览

热门推荐

通过挑战的用户