Summary of usage of commonly used functions in PAT Class B

PAT Computer Programming Aptitude Test

 1. Matters needing attention

  1. All the questions can be solved with the most basic knowledge of C language. Some of them need to use structures, and the most involved data structures are linked lists. The most commonly used functions are strcmp, strcpy, qsort, abs, fabs, etc.
  2. It is best to set a large array as a global, because the main function is in the stack space, and the size of the stack is only tens of KB. If the array is too large, a stack overflow will occur. Therefore, a large array is set as a global. Global variables occupy heap space, and the heap space is allocated on demand. , can be large or small
  3. For errors, the newline at the end does not affect the format.
           Segmentation faults generally mean that the set array is smaller than the requirements given by the question. The wrong
           answer usually means that there is an error in the code logic.
           Running timeout means that the question cannot be cracked by brute force, or i-- is written as i++ or the like error in the loop body of
  4. For test cases, it is best to bring them to DEV C++ or other compilers for testing. Generally, many errors can be found for easy correction.
  5. %s in scanf cannot receive parameters of string type, otherwise garbled characters will appear, because %s is a format specifier for reading strings, and &s is the address of a string object, not a pointer to a character array:
    string s;
    scanf("%s", &s); 
    //可以把scanf改为cin解决问题
    string s;
    cin >> s;
  6. For the timeout, it may be caused by cin input data:
    scanf("%d",&elem);  // 元素的类型我们已经告知了,机器不用再去查找元素类型。
    
    cin >> elem;  // 元素类型由机器自己查找,在需要大量输入数据的时候,时间的冗余就十分明显了
    

    Someone once made a comparison: in the case of the same amount of data, the time consumption of cin is 3.5~4 times that of scanf.
    However, it is worth mentioning that the security of cin is superior to that of scanf.

  7. For questions with strict time requirements (PAT Class B 2022 Spring Exam 7-5 K large numbers), you can consider using multiplication and division as little as possible, and use array operations instead of using STL.

  8. %.f will be rounded automatically. If the meaning of the question requires the result to be rounded down, such as 1070 knots , you can use mandatory type conversion.

    printf("%.f", ans);      //结果四舍五入
    printf("%d", (int)ans);  //结果向下取整
  9. To get a line of data that contains spaces, you can use getline(), getline() encounters a carriage return ('\n') input and ends.

    getline(cin, str); //getline()不会将末尾的"\n"保存到str中
  10. AC and the code are completely correct. If you can determine the specific input and output of the point that failed, you can make a special judgment. For example, if you know that the data of test point 4 is 25000, but the code does not work, it is in the main loop insert

    if(n == 25000)
        printf("No Solution");

    This is just an example, see Qingshen PAT machine test skills for specific skills


2. Commonly used functions

1. sort()  sorting function

bool cmp(struct node a,struct node b) {
	if ((a.de + a.cai) != (b.de + b.cai))
		return (a.de + a.cai) > (b.de + b.cai);
	else if (a.de != b.de)
		return a.de > b.de;
	else
		return a.num < b.num;
}
struct node
{
	int num, de, cai;
}v[4];
sort(v[i].begin(), v[i].end(), cmp);

or

struct node
{
	int num, de, cai;
	friend bool operator < (node& a, node& b) {
		if ((a.de + a.cai) != (b.de + b.cai))
			return (a.de + a.cai) > (b.de + b.cai);
		else if (a.de != b.de)
			return a.de > b.de;
		else
			return a.num < b.num;
	}
};
sort(v[i].begin(), v[i].end());

The sort function defaults to ascending order, if you need descending order, you can

sort(v[i].begin(), v[i].end(), greater<int>()); //降序
sort(v[i].begin(), v[i].end(), less<int>()); //升序

or

bool cmp(int a, int b){
    return a > b;
}
sort(a.begin(), a.end(), cmp);

2. substr()  to get the substring

string s = "123456";
cout << s.substr(2, 3);
  • Output result: 345

3. reverse()  inverts the function

char res[10] = "abcdefghi";
reverse(begin(res), begin(res) + 4);
cout << res;
  • Output: dcbaefghi

4. Common operations of vector 

vector<int>  v1(n,1);//初始化一个大小为n,值全为1的数组

v1.push_back(2);//在vector末尾插入元素2
v1.pop_back();//删除vector末尾元素

v1.insert(v1.begin(),3);//在v1第一个位置前插入3
v1.insert(v1.begin()+1,4);//在v1第二个位置前插入4
v1.insert(v1.begin(),5,6);//在v1第一个位置前连续插入5个6

v1.erase(v1.begin());//删除第一个元素
v1.erase(v1.begin()+1);//删除第二个元素
v1.erase(v1.begin(),v1.begin()+3);//删除前三个元素

5, itoa() atoi() stoi() to_string() conversion

int i = 579;
char s[10];
itoa(i, s, 8); //第三个参数为转换的进制数
cout << s;
  • itoa() output result: 1103
char s[4] = "107";
int num = atoi(s);
cout << num;
string s = "107";
int num = atoi(s.c_str());
cout << num;
  • atoi() output result: 107
char s[4] = "107";
int num = stoi(s);
cout << num;
  • stoi() output result: 107
int num = 19732;
string s = to_string(num);
s += "777";
cout << s;
  • to_string() output result: 19732777

6. isdigit()  & isalpha() & isalnum() & isupper() & islower() to determine whether a character is an alphanumeric character

char a = '7', b = 'C';
cout << isdigit(a) << " " << isdigit(b) << "\n"; //判断是否是数字
cout << isalpha(a) << " " << isalpha(b) << "\n"; //判断是否是字母
cout << isalnum(a) << " " << isalnum(b) << "\n"; //判断是否是数字或字母
cout << isupper(a) << " " << isupper(b) << "\n"; //判断是否是大写字母
cout << islower(a) << " " << islower(b) << "\n"; //判断是否是小写字母
  • Output result:
    4 0
    0 1
    4 1
    0 1
    0 0

7. round() rounds

#define CLK_TCK 100
double t1 = 100, t2 = 149, t3 = 150;
cout << round((t2 - t1) / CLK_TCK) << " " << round((t3 - t1) / CLK_TCK);
  • Output result: 0 1

8. toupper() & tolower() convert case

char a = 'a', b = 'B';
cout << toupper(a) << " " << tolower(b);
  • Output result: 65 98

9. string::npos  usage

string s = "abcdefg";
int idx = s.find('.');   //作为return value,表示没有匹配项
if (idx == string::npos)
    cout << "This string does not contain any period!" << endl;
idx = s.find('c');
s.replace(idx + 1, string::npos, "x");  //string::npos作为长度参数,表示直到字符串结束
cout << s;
  • Output result:
    This string does not contain any period!
    abcx

10. upper_bound() & lower_bound() to find the upper and lower bounds

  • Note: What is returned here is the address, and the subscript is obtained by subtracting the array name.
  • upper_bound()  looks for boundaries smaller than the specified value (finds the first position greater than 3), lower_bound()  looks for boundaries greater than or equal to the specified value (finds the first position greater than or equal to 3)
vector<int> nums = { 1, 2, 3, 3, 4, 4, 5 };
int index = upper_bound(nums.begin(), nums.end(), 3) - nums.begin();
cout << index << endl; // >: 4
index = lower_bound(nums.begin(), nums.end(), 3) - nums.begin();
cout << index << endl; // >: 2
  • Output result: 4 2

11. map usage

map : A red-black tree is implemented inside the map. This structure has the function of automatic sorting, so all elements inside the map are in order. Each node of the red-black tree represents an element of the map. Therefore, for the map A series of operations such as searching, deleting, and adding are equivalent to performing such operations on the red-black tree, so the efficiency of the red-black tree determines the efficiency of the map.
unordered_map : unordered_map internally implements a hash table, so the query efficiency of unordered_map is very high, but the order of its elements is messy and unordered.

  1. Map traversal
    map<char, int> mp;
    char c;
    while ((c = cin.get()) != '\n') 
    	if(isalpha(c))
    		mp[c]++;
    for (map<char, int>::iterator it = mp.begin(); it != mp.end(); it++) {
    	printf("%c %d  ", it->first, it->second);
    }
    or
    #include<unordered_map>
    unordered_map<char, int> mp;
    char c;
    while ((c = cin.get()) != '\n') 
    	if(isalpha(c))
    		mp[c]++;
    for (auto it = mp.begin(); it != mp.end(); it++) {
    	printf("%c %d  ", it->first, it->second);
    //auto获取的是一个值的拷贝,而不是指针
    for (auto it:mp) {
    	printf("%c %d  ", it.first, it.second);
    }	
    //auto&获取的是指针,所以可以修改具体的键值
    for (auto &it:mp) {
    	printf("%c %d  ", it.first, it.second);
    }
    }

    enter:
    This is a simple TEST.

    output:

    E 1  S 1  T 3  a 1  e 1  h 1  i 3  l 1  m 1  p 1  s 3
  2. Map common operations

    begin() 返回指向 map 头部的迭代器
    clear() 删除所有元素
    count() 返回指定元素出现的次数
    empty() 如果 map 为空则返回 true
    end() 返回指向 map 末尾的迭代器
    erase() 删除一个元素
    find() 查找一个元素
    insert() 插入元素
    key_comp() 返回比较元素 key 的函数
    lower_bound() 返回键值>=给定元素的第一个位置
    max_size() 返回可以容纳的最大元素个数
    rbegin() 返回一个指向 map 尾部的逆向迭代器
    rend() 返回一个指向 map 头部的逆向迭代器
    size() 返回 map 中元素的个数
    swap() 交换两个 map
    upper_bound() 返回键值>给定元素的第一个位置
    value_comp() 返回比较元素 value 的函数
    


 12. Set collection usage

set is a container that is automatically ordered internally and does not contain duplicate elements.

The main function of set is to automatically deduplicate and sort in ascending order, which is suitable for situations where deduplication is required but it is inconvenient to open the array directly.

The elements in the set are unique, and it is implemented internally using a "red-black tree".

  1. definition of set
    set<int> st;
  2. set traversal
    set<int> st;
    for (auto it = st.begin(); it != st.end(); it++) {
    	cout << *it << endl;
    }
  3. Common operations of set
    begin() 返回指向第一个元素的迭代器
    clear() 清除所有元素
    count() 返回某个值元素的个数
    empty() 如果集合为空,返回true(真)
    end() 返回指向最后一个元素之后的迭代器,不是最后一个元素
    equal_range() 返回集合中与给定值相等的上下限的两个迭代器
    erase() 删除集合中的元素
    find() 返回一个指向被查找到元素的迭代器
    get_allocator() 返回集合的分配器
    insert() 在集合中插入元素
    lower_bound() 返回指向大于(或等于)某值的第一个元素的迭代器
    key_comp() 返回一个用于元素间值比较的函数
    max_size() 返回集合能容纳的元素的最大限值
    rbegin() 返回指向集合中最后一个元素的反向迭代器
    rend() 返回指向集合中第一个元素的反向迭代器
    size() 集合中元素的数目
    swap() 交换两个集合变量
    upper_bound() 返回大于某个值元素的迭代器
    value_comp() 返回一个用于比较元素间的值的函数

13. sscanf() & sprintf() usage

  • sscanf() – reads data from a string that matches the specified format
  • sprintf() – string formatting command, the main function is to write formatted data into a string 
scanf("%s", str1);
sscanf(str1, "%lf", &temp);		//在str1中读取一个浮点数给temp
sprintf(str2, "%.2lf", temp);	//把temp以保留两位小数的字符串形式给str2

 enter:

aaa 
2.3.4 
1.23ab2.3

output:

aaa 0 0.00
2.3.4 2.3 2.30
 1.23 1.23

 It is worth noting that the return value of sscanf() is the number of data read : for example, sscanf(ch, "%d(%d)%d", &a, &b, &c), the return value is the number of read a , the number of b, c


3. Common algorithms 

1. isPrime : find a prime number

bool isPrime(int a) {
	if (a == 0 || a == 1) return false;
	for (int i = 2; i <= sqrt(a); i++) {
		if (a % i == 0)return false;
	}
	return true;
}

2. gcd (greatest common divisor) : find the greatest common divisor by rolling and dividing

int gcd(int a, int b)
{
	return b == 0 ? a : gcd(b, a % b);
}
  • Output result: gcd(21, 27) = 7

3. lcm (least common multiple) : least common multiple

int lcm(int a, int b) {
    return a * b / gcd(a, b);
}

4. dfs : depth-first search algorithm

void dfs(int step){    
	剪枝{
		相应操作;
		return;
	}
    判断边界{
        相应操作;
        return;
    }
    尝试每一种可能{
        满足check条件{
            标记;
            继续下一步dfs(step+1);
            恢复初始状态(回溯的时候要用到);
        }
    }
} 

Guess you like

Origin blog.csdn.net/qq_21891843/article/details/124900085