PAT 算法笔记 A1039

原题目

自己第一遍的解法

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct people{
	char name[3];
	int course_num=0;
	vector<int> course_array;
};
int main(){
	int n,k;
	cin>>n>>k;
	people student[n];
	for(int i=0;i<k;i++){
		int course_id;
		int num;
		cin>>course_id>>num;
		for(int j=0;j<num;j++){
			char name[4];
			cin>>name;
			int index=int(name[3]-'0');
			//名字赋值时有没有更好的方法??? 
			student[index].name[0]=name[0];
			student[index].name[1]=name[1];
			student[index].name[2]=name[2];
			student[index].course_num++;
			student[index].course_array.push_back(course_id);
		}
	}
	char search[n][4];
	for(int i=0;i<n;i++){
		cin>>search[i];
	}
	for(int i=0;i<n;i++){
		//35-37 为什么search[i]输出的不是search[i][0]-search[i][3]呢? 
		for(int k=0;k<4;k++){
			cout<<search[i][k];
		}
		cout<<" ";
		int index=int(search[i][3]-'0');
		cout<<student[index].course_num<<" ";
		sort(student[index].course_array.begin(),student[index].course_array.end());
		for(int j=0;j<student[index].course_array.size();j++){
			cout<<student[index].course_array[j]<<" ";
		}
		cout<<endl;
	}
} 

好的解法

我存在的问题

  1. 审题错误。我实现名字与数字的对应是通过第4位的数字去实现,误以为每个人名字的最后一位不重复。事实上有4 0000个人,是绝对会有数字重复的
  2. 字符串的处理很低劣。
  3. 二维数组知识的欠缺。
  4. 数据量庞大的题目,不应该使用cin cout,要用scanf 和pringf。因为cin和cout效率低,容易造成超时导致错误发生。另外scnaf以%s形式输入时,会自动在字符串末尾加上'\0'。

改进与学习

1.使用字符串hash来实现名字与数字的对应。把名字的前3位看成是26进制数,将它转换为10进制,然后再乘以10,最后加上第4位的数字。这样做的hash函数,实现了名字与数字的唯一对应

2.字符串的处理

字符串的截取:substr(pos,n)  返回一个string,包含s中从pos开始的n个字符的拷贝

#include<string>

#include<iostream>

using namespace std;

int main()

{

  string s("12345asdf"); 

  string a = s.substr(0,5);     //获得字符串s中从第0位开始的长度为5的字符串

  cout << a << endl;

}

输出结果为:12345

note:

 a.    string str("value")  是string类型的一种初始化方式

 b.    该函数的使用要有 #include <string>

 

3. 使用char 型的二维数组s存放字符串,一定要有'\0'作为字符串结束标志,否则输出s[0]时,将会把所有的字符串一起输出。

#include <iostream>
using namespace std;
int main(){
	char a[3][3];
	for(int i=0;i<3;i++){
		for(int j=0;j<3;j++){
			cin>>a[i][j];
		}
	}
	cout<<a[0];
}

输入:

AAA

BBB

CCC

输出:AAABBBCC

#include <iostream>
using namespace std;
int main(){
	char a[3][3];
	for(int i=0;i<3;i++){
		for(int j=0;j<3;j++){
			cin>>a[i][j];
		}
	}
	a[1][0]='\0';
	cout<<a[0];
}

加上'\0'后,顺利输出:AAA

 

收获

1.一种避免输出多余空格的方法

瞧, "  %d",空格在前头,所以后面不会有多余的空格。但这种情况只能在前面也有数据的时候使用。

2.字符串hash

通过将字符串看成是26进制数,把它转换为10进制数,即可把大写字母构成的字符串转换为唯一对应的数字。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值