1 字符串处理

1001 A+B Format (20 分)

Calculate a+b and output the sum in standard format — that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input:

-1000000 9结尾无空行

Sample Output:

-999,991

toString ()方法用于返回以一个字符串表示的 Number 对象值。 (可以正常转换正负号

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int a,b;
  6. cin >> a>> b;
  7. int c= a+b;
  8. string num = to_string(c);
  9. string res;
  10. for(int i = num.size()-1,j =0; i >=0;i--)
  11. {
  12. res =num[i]+res;
  13. ++j;
  14. if(j % 3 ==0 && i && num[i-1] != '-') res= ',' +res;
  15. }
  16. cout <<res <<endl;
  17. }

1005 Spell It Right (20 分)

Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.

Input Specification:

Each input file contains one test case. Each case occupies one line which contains an N (≤10100).

Output Specification:

For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.

Sample Input:

12345结尾无空行

Sample Output:

one five结尾无空行

Code
通过先读入字符串,然后利用for(auto c:num)遍历字符串的每一个数字,`c -‘0’来把字符转换为int类型的数字

数字和英文转换用if-else也可以写,但是太麻烦
定义char类型数组
char word[10][10]= { “zero”,”one”,”two”,”three”,”four”, “five”,”six”,”seven”,”eight”,”nine”,};
来和0 1 2 ··· 一一对应

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main()
{
    string num;
    cin >>num;

    int sum= 0;
    for( auto c:num ) sum += c-'0';

    char word[10][10] ={"zero","one","two","three","four","five","six","seven","eight","nine"};
    string str=to_string(sum);
    cout<<word[str[0]-'0'];
    for(int i = 1; i < str.size();i++) cout << ' ' << word[str[i]-'0'];

    return 0;
}

1006 Sign In and Sign Out (25 分)

At the beginning of every day, the first person who signs in the computer room will unlock the door, and the last one who signs out will lock the door. Given the records of signing in’s and out’s, you are supposed to find the ones who have unlocked and locked the door on that day.

Input Specification:

Each input file contains one test case. Each case contains the records for one day. The case starts with a positive integer M, which is the total number of records, followed by M lines, each in the format:
ID_number Sign_in_time Sign_out_time
where times are given in the format HH:MM:SS, and ID_number is a string with no more than 15 characters.

Output Specification:

For each test case, output in one line the ID numbers of the persons who have unlocked and locked the door on that day. The two ID numbers must be separated by one space.
Note: It is guaranteed that the records are consistent. That is, the sign in time must be earlier than the sign out time for each person, and there are no two persons sign in or out at the same moment.

Sample Input:

3 CS301111 15:30:28 17:00:10 SC3021234 08:00:00 11:25:25 CS301133 21:45:00 21:58:40结尾无空行

Sample Output:

SC3021234 CS301133结尾无空行
时间可以直接用字典序比较,这种格式可以直接读入string

if(!i || in_time<open_time)一定要有!i的条件,确保i=0的时候先进行赋值比较,不然的话会一直没有值读入进去

#include <iostream>


using namespace std;
int main()
{
    string open_id, open_time;
    string close_id, close_time;

    int m;

    cin >>m;
    for(int i =0; i <m; i++)
    {
        string id, in_time,out_time;
        cin>> id >>in_time>>out_time;
        //更新开门人
        if(!i || in_time<open_time)
        {
            open_id =id;
            open_time=in_time;
        }
        //更新锁门人
        if(!i || out_time >close_time)
        {
            close_id= id;
            close_time=out_time;
        }
    }
    cout << open_id<< ' ' <<close_id;
}

1035 Password (20 分)

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 0<_N_<100, the number of nodes in a tree, and _M_ (<_N_), the number of non-leaf nodes. Then _M_ lines follow, each in the format:
ID K ID[1] ID[2] … ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID’s of its children. For the sake of simplicity, let us fix the root ID to be 01.
The input ends with N being 0. That case must NOT be processed.

Output Specification:

For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.
The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output 0 1 in a line.

Sample Input:

2 1 01 1 02结尾无空行

Sample Output:

0 1结尾无空行
pta代码未完成

#include <iostream>

using namespace std;
const int N =1010;
string name[N],pwd[N];
string change(string str)
{
    string res;
    for(auto c:str){
        if(c=='1') res +='@';
        else if( c== '0') res+='%';
        else if( c=='l') res+='L';
        else if(c=='O') res +='o';
        else res +=c;
    }
    return res;
}
int main(){
    int n;
    cin >>n;
    int m=0;

    for(int i =0; i< n; i++){
        string cur_name,cur_pwd;
        cin >> cur_name>> cur_pwd;
        string changed_pwd;
        changed_pwd= change(cur_pwd);
        if(changed_pwd  != cur_pwd)
        {

            name[m]=cur_name;
            pwd[m]=changed_pwd;
            m ++;
        }
    }
    if(!m){
        if(n ==1) printf("There is 1 account and no account is modified");
        else printf("There are %d accounts and no account is modified",n);
    }else{
        cout<<m<<endl;
        for(int i =0; i<m;i++){
            cout << name[i]<< ' '<<pwd[i]<< endl;
            }
     }

}

1036 Boys vs Girls (25 分)

This time you are asked to tell the difference between the lowest grade of all the male students and the highest grade of all the female students.

Input Specification:

Each input file contains one test case. Each case contains a positive integer N, followed by N lines of student information. Each line contains a student’s name, gender, ID and grade, separated by a space, where name and ID are strings of no more than 10 characters with no space, gender is either F (female) or M (male), and grade is an integer between 0 and 100. It is guaranteed that all the grades are distinct.

Output Specification:

For each test case, output in 3 lines. The first line gives the name and ID of the female student with the highest grade, and the second line gives that of the male student with the lowest grade. The third line gives the difference gradeFgradeM. If one such kind of student is missing, output Absent in the corresponding line, and output NA in the third line instead.

Sample Input 1:

3 Joe M Math990112 89 Mike M CS991301 100 Mary F EE990830 95结尾无空行

Sample Output 1:

Mary EE990830 Joe Math990112 6
结尾无空行

Sample Input 2:

1 Jean M AA980920 60
结尾无空行

Sample Output 2:

Absent Jean AA980920 NA
结尾无空行

#include <iostream>
using namespace std;
int main(){
    int n;
    cin >>n;
    string boy_name,boy_id;
    int boy_score;
    string girl_name,girl_id;
    int girl_score;

    for(int i =0; i<n;i++){
        string name,id,sex;
        int score;
        cin >>name>> sex>>id>>score;
        if(sex == "M"){
            if(boy_id.empty() || score< boy_score){
                boy_score=score;
                boy_name=name;
                boy_id=id;
            }
        }else{
            if(girl_id.empty() || score> girl_score){
                girl_score=score;
                girl_name=name;
                girl_id=id;
            }

        }
    }

    if(girl_id.empty()) puts("Absent");
    else cout <<girl_name<< ' '<<girl_id<<endl;
    if(boy_id.empty()) puts("Absent");
    else cout <<boy_name<< ' '<<boy_id<<endl;
    if(!girl_id.empty() && !boy_id.empty()) cout << girl_score-boy_score;
    else puts("NA");
}

girl_id.empty()可以方便判断这个值是不是为空,

1050 String Subtraction (20 分)

Given two strings S_1 and _S_2, _S=_S_1−_S_2 is defined to be the remaining string after taking all the characters in _S_2 from _S_1. Your task is simply to calculate _S_1−_S_2 for any given strings. However, it might not be that simple to do it fast.

Input Specification:

Each input file contains one test case. Each case consists of two lines which gives _S_1 and _S_2, respectively. The string lengths of both strings are no more than 104. It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.

Output Specification:

For each test case, print _S_1−_S_2 in one line.

Sample Input:

They are students. aeiou结尾无空行

Sample Output:

Thy r stdnts.结尾无空行

#include <iostream>
#include <unordered_set>

using namespace std;
string s1,s2;
int main(){
    getline(cin,s1);
    getline(cin,s2);

    unordered_set<char> hash;//定义char类型哈希表
    for(auto c:s2) hash.insert(c);// 把s1字符压入哈希表
    string res;

    for(auto c:s1){
        if(!hash.count(c)) res+=c;//返回c出现的数量,如果为0执行res+=c
    }
    cout << res<< endl;

}

#include <unordered_set>哈希表头文件
unordered_set<char> hash;定义char类型哈希表
for(auto c:s2) hash.insert(c);把s1字符压入哈希表
hash.count(c)返回哈希表中c出现的数量

1071 Speech Patterns (25 分)

People often have a preference among synonyms of the same word. For example, some may prefer “the police”, while others may prefer “the cops”. Analyzing such patterns can help to narrow down a speaker’s identity, which is useful when validating, for example, whether it’s still the same person behind an online avatar.
Now given a paragraph of text sampled from someone’s speech, can you find the person’s most commonly used word?

Input Specification:

Each input file contains one test case. For each case, there is one line of text no more than 1048576 characters in length, terminated by a carriage return \n. The input contains at least one alphanumerical character, i.e., one character from the set [0-9 A-Z a-z].

Output Specification:

For each test case, print in one line the most commonly occurring word in the input text, followed by a space and the number of times it has occurred in the input. If there are more than one such words, print the lexicographically smallest one. The word should be printed in all lower case. Here a “word” is defined as a continuous sequence of alphanumerical characters separated by non-alphanumerical characters or the line beginning/end.
Note that words are case insensitive.

Sample Input:

Can1: “Can a can can a can? It can!”结尾无空行

Sample Output:

can 5结尾无空行

#include <iostream>
#include <unordered_map>//哈希map

using namespace std;


//judge whether the char belong to letter or number
bool check(char c){
    if(c >='0' && c<='9') return true;
    if(c >='a' && c<='z') return true;
    if(c >='A' && c<='Z') return true;
    return false;
}

int main(){
    string str;
    getline(cin,str);//cin the whole line including spaces

    unordered_map<string,int> hash;//create a hash map
    //i j dual pointer
    for(int i =0; i<str.size();i++){
        if(check(str[i])){
            string word;
            int j =i;
            while(j <str.size() && check(str[j])){
                word+=tolower(str[j]);//change the upper letter to the lower letter
                j++;
            }
            hash[word] ++;//put the word into the hash
            i =j;//after the word is finish,start the new i at the last j location
        }
    }

    string word;
    int cnt=-1;//makesure that item.second >cnt
    for(auto item:hash)
        if(item.second>cnt||(item.second ==cnt && item.first < word)){
            word=item.first;
            cnt=item.second;
        }


    cout << word<<' '<< cnt<<endl;
}

利用hash map

利用双指针
判断是否是字母大小写或者数字单独用一个函数

1061 Dating (20 分)

Sherlock Holmes received a note with some strange strings: Let’s date! 3485djDkxh4hhGE 2984akDfkkkkggEdsb s&hgsfdk d&Hyscvnm. It took him only a minute to figure out that those strange strings are actually referring to the coded time Thursday 14:04 — since the first common capital English letter (case sensitive) shared by the first two strings is the 4th capital letter D, representing the 4th day in a week; the second common character is the 5th capital letter E, representing the 14th hour (hence the hours from 0 to 23 in a day are represented by the numbers from 0 to 9 and the capital letters from A to N, respectively); and the English letter shared by the last two strings is s at the 4th position, representing the 4th minute. Now given two pairs of strings, you are supposed to help Sherlock decode the dating time.

Input Specification:

Each input file contains one test case. Each case gives 4 non-empty strings of no more than 60 characters without white space in 4 lines.

Output Specification:

For each test case, print the decoded time in one line, in the format DAY HH:MM, where DAY is a 3-character abbreviation for the days in a week — that is, MON for Monday, TUE for Tuesday, WED for Wednesday, THU for Thursday, FRI for Friday, SAT for Saturday, and SUN for Sunday. It is guaranteed that the result is unique for each case.

Sample Input:

3485djDkxh4hhGE 2984akDfkkkkggEdsb s&hgsfdk d&Hyscvnm结尾无空行

Sample Output:

THU 14:04结尾无空行

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    string a,b,c,d;
    cin>>a>>b>>c>>d;

    int k=0;
    while(true){
        if(a[k]==b[k] && a[k] >='A' && a[k]<='G') break;
        k++;
    }

    char weekdays[7][4] ={"MON","TUE","WES","THU","FRI","SAT","SUN"};
    printf("%s",weekdays[a[k]-'A']);

    k++;
    while(true)
    {
        if(a[k]==b[k] && (a[k]>='0' && a[k]<='9' || a[k] >='A' && a[k] <= 'N')) break;
        k++;
    }
    printf("%02d:",a[k] <='9' ? a[k]-'0' : a[k]-'A'+10);

    for(int i =0;;i++)
        if(c[i] ==d[i] && (c[i]>='a' && c[i] >='z' || c[i] >='A' && c[i] <='Z'))
        {
            printf("%02d\n",i);
            break;
        }
    return 0;
}

这种不考虑没有结果,只用break的情况,如果超时,首先排除是不是判断写的有问题

1016 Phone Bills (25 分)

A long-distance telephone company charges its customers by the following rules:
Making a long-distance call costs a certain amount per minute, depending on the time of day when the call is made. When a customer starts connecting a long-distance call, the time will be recorded, and so will be the time when the customer hangs up the phone. Every calendar month, a bill is sent to the customer for each minute called (at a rate determined by the time of day). Your job is to prepare the bills for each month, given a set of phone call records.

Input Specification:

Each input file contains one test case. Each case has two parts: the rate structure, and the phone call records.
The rate structure consists of a line with 24 non-negative integers denoting the toll (cents/minute) from 00:00 - 01:00, the toll from 01:00 - 02:00, and so on for each hour in the day.
The next line contains a positive number N (≤1000), followed by N lines of records. Each phone call record consists of the name of the customer (string of up to 20 characters without space), the time and date (MM:dd:HH:mm), and the word on-line or off-line.
For each test case, all dates will be within a single month. Each on-line record is paired with the chronologically next record for the same customer provided it is an off-line record. Any on-line records that are not paired with an off-line record are ignored, as are off-line records not paired with an on-line record. It is guaranteed that at least one call is well paired in the input. You may assume that no two records for the same customer have the same time. Times are recorded using a 24-hour clock.

Output Specification:

For each test case, you must print a phone bill for each customer.
Bills must be printed in alphabetical order of customers’ names. For each customer, first print in a line the name of the customer and the month of the bill in the format shown by the sample. Then for each time period of a call, print in one line the beginning and ending time and date (dd:HH:mm), the lasting time (in minute) and the charge of the call. The calls must be listed in chronological order. Finally, print the total charge for the month in the format shown by the sample.

Sample Input:

10 10 10 10 10 10 20 20 20 15 15 15 15 15 15 15 20 30 20 15 15 10 10 10 10 CYLL 01:01:06:01 on-line CYLL 01:28:16:05 off-line CYJJ 01:01:07:00 off-line CYLL 01:01:08:03 off-line CYJJ 01:01:05:59 on-line aaa 01:01:01:03 on-line aaa 01:02:00:01 on-line CYLL 01:28:15:41 on-line aaa 01:05:02:24 on-line aaa 01:04:23:59 off-line结尾无空行

Sample Output:

CYJJ 01 01:05:59 01:07:00 61 $12.10 Total amount: $12.10 CYLL 01 01:06:01 01:08:03 122 $24.40 28:15:41 28:16:05 24 $3.85 Total amount: $28.25 aaa 01 02:00:01 04:23:59 4318 $638.80 Total amount: $638.80结尾无空行

#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 10010;
const int M = 31 * 1440 +10;
int n;
int cost[24];
double sum[M];

struct Record{
    int minutes;
    string state;
    string format_time;

    bool operator< (const Record& t) const{
        return minutes < t.minutes;
    }

};

map<string, vector<Record>> persons;


int main(){
    for ( int i =0; i < 24; i ++ ) cin >> cost[i];
    for ( int i =0; i < M; i ++ ) sum[i] = sum[i-1] + cost[(i-1) % 1440 / 60 ]/100.0;
    cin >> n;
    char name[25],state[10],format_time[20];
    int month, day, hour, minute;


    for(int i = 0; i < n; i++)
    {
        scanf("%s %d:%d:%d:%d %s", name, &month, &day, &hour, &minute, state);
        sprintf(format_time, "%02d:%02d:%02d", day, hour, minute);

        int minutes  = (day-1) *1440 + hour *60 + minute;
        persons[name].push_back({minutes,state,format_time});
    }

    for (auto &person : persons){
        auto name = person.first;
        auto records = person.second;
        sort(records.begin(), records.end());

        double total = 0;
        for (int i =0; i + 1 < records.size(); i ++ ){
            auto a = records[i], b = records[i + 1];
            if(a.state == "on-line" && b.state == "off-line"){
                if(!total) printf("%s %02d\n", name.c_str(), month);
                cout << a.format_time << ' ' << b.format_time;

                double c = sum[b.minutes] - sum[a.minutes];
                printf(" %d $%.2lf\n", b.minutes - a.minutes, c);
                total +=c;

            }
        }
        if(total) printf("Total amount: $%.2lf\n",total);
    }
    return 0;
}

代码量一大,容易出bug
注意掉包和对map的理解

1017 Queueing at Bank (25 分)

Suppose a bank has K windows open for service. There is a yellow line in front of the windows which devides the waiting area into two parts. All the customers have to wait in line behind the yellow line, until it is his/her turn to be served and there is a window available. It is assumed that no window can be occupied by a single customer for more than 1 hour.
Now given the arriving time T and the processing time P of each customer, you are supposed to tell the average waiting time of all the customers.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 numbers: N (≤104) - the total number of customers, and K (≤100) - the number of windows. Then N lines follow, each contains 2 times: HH:MM:SS - the arriving time, and P - the processing time in minutes of a customer. Here HH is in the range [00, 23], MM and SS are both in [00, 59]. It is assumed that no two customers arrives at the same time.
Notice that the bank opens from 08:00 to 17:00. Anyone arrives early will have to wait in line till 08:00, and anyone comes too late (at or after 17:00:01) will not be served nor counted into the average.

Output Specification:

For each test case, print in one line the average waiting time of all the customers, in minutes and accurate up to 1 decimal place.

Sample Input:

7 3 07:55:00 16 17:00:01 2 07:59:59 15 08:01:00 60 08:00:00 30 08:00:02 2 08:03:00 10结尾无空行

Sample Output:

8.2结尾无空行

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <vector>

using namespace std;

const int N = 1010;
int n,m;

struct Person{
    int arrive_time;
    int service_time;

    bool operator< (const Person& t) const{
        return arrive_time < t.arrive_time;
    }
}persons[N];

int main(){
    cin >> n >> m;
    for ( int i = 0; i < n; i ++){
        int hour, minute, second, service_time;
        scanf("%d:%d:%d %d", &hour, &minute, &second, &service_time);

        service_time = min(service_time, 60);

        persons[i] = {hour * 3600 + minute * 60 + second, service_time * 60};
    }

    priority_queue<int, vector<int>, greater<int>> windows;

    for (int i =0; i < m; i ++) windows.push( 8 * 3600);
    sort(persons, persons + n);
    int sum =0, cnt =0;
    for( int i =0 ; i < n; i ++){
        auto person = persons[i];
        if (person.arrive_time > 17 * 3600) break;
        int w =windows.top();
        windows.pop();

        //printf("%d %d\n",person.arrive_time, w);
        int start_time = max(person.arrive_time, w);
        sum += start_time - person.arrive_time;
        cnt ++;
        windows.push(start_time+person.service_time);

    }
    printf("%.1lf\n",(double)sum /cnt /60);


    return 0;


}

1073 Scientific Notation (20 分)

#include <iostream>
#include <string>
using namespace std;

int main(){
    string s;
    cin >> s;
    if(s[0] =='-') cout << "-";
    int k = s.find("E");

    string a = s[1] + s.substr(3, k-3);
    //cout <<a;
    int b = stoi(s.substr(k+1));
    //cout <<b<<endl;
    b++;
    if(b <=0)  a = "0." +string(-b, '0') + a;
    else if( b >=s.size()) a = a + string(b-a.size(),'0');
    else a =a.substr(0,b) + '.' + a.substr(b);

    cout << a;
}

1077 Kuchiguse (20 分)

#include <iostream>

using namespace std;

const int N = 110;

int n;

string s[N];

int main(){
    cin >> n;
    getchar();//    把回车读取, 再读取每一行
    for (int i =0; i< n; i ++){
        getline(cin,s[i]);
    }
//    后缀长度为 s[0]长度
//    后缀长度为 s[0]长度-1
//    ... 直到sf.size() == s[0].size() 暴力枚举每一种可能的公共后缀

    for (int k = s[0].size(); k ; k--){

        string sf = s[0].substr(s[0].size() - k);//取后缀

        bool is_matched =true;//标记后缀是否相等

        //遍历每一行
        for (int i =1; i < n; i ++){
            //当sf后缀大于s[i]长度或者
            if(k > s[i].size() || s[i].substr(s[i].size()-k) != sf){
                is_matched = false;
                break;
            }
        }

        if(is_matched){
            cout << sf << endl;

            return 0;
        }
    }

    puts("nai");

    return 0;
}


1084 Broken Keyboard (20 分)

#include <iostream>

using namespace std;
//定义一个判断数组,用于判断某一个字符是否已经被发现键盘损坏输出过了,200是确定大于ascii的值,所有定在200
bool st[200] = {0};

int main(){
    string a,b;
    cin >> a >> b;
    for( int i =0, j =0; i < a.size(); i++){
        char x=toupper(a[i]), y = toupper(b[j]);//统一转换为大写

        //双指针,如果x=y,指针一起向后移
        if( x == y) j++;
        else if( !st[x]) cout << x, st[x] =1;
    }

    return 0;
}


try =catch 语句

#include <iostream>

using namespace std;

int main(){
    int n;
    cin >> n;
    int cnt = 0;
    double sum = 0;
    while(n--){
        string num;
        cin >> num;
        double x;

        bool success = true;
        try{
            size_t idx;
            x =stof(num, &idx);

            if(idx < num.size()) success = false;
        }catch(...){
            success = false;
        }
        //判断大小是否在范围内
        if( x < -1000 || x > 1000) success = false;

        //判断小数点是不是后两位
        int k = num.find('.');
        if( k != -1 && (num.size() - k) > 3) success = false;

        if (success) cnt ++, sum+=x;
        else printf("ERROR: %s is not a legal number\n",num.c_str());


    }

    if( cnt > 1) printf("The average of %d numbers is %.2lf",cnt, sum /cnt);
    else if (cnt ==1) printf("The average of 1 number is %.2lf",sum);
    else printf("The average of 0 numbers is Undefined");
}
#include <iostream>
#include <unordered_set>

using namespace std;

const int N = 1010;

int m, n,s;
string name[N];

int main(){
    cin >> m >> n >> s;
    for (int i =1 ; i <= m; i ++) cin >> name[i];
    unordered_set<string> hash;

    int k = s;
    while( k <= m){
        if(hash.count(name[k])) k ++;
        else{
            cout << name[k] << endl;
            hash.insert(name[k]);
            k +=n;
        }
    }

    if(hash.empty()) puts("Keep going...");
    return 0;
}
#include <iostream>
#include <cstring>
#include <unordered_map>
#include <vector>
#include <algorithm>

using namespace std;


struct School{
    string name;
    int cnt;
    double sum;
    //默认构造
    School(): cnt(0), sum(0) {}

    bool operator< (const School &t) const{
        if (sum != t.sum ) return sum >t.sum;
        if (cnt != t.cnt) return cnt < t.cnt;
        return name < t.name;
    }
};
int main(){
    int n;
    cin >> n;
    unordered_map<string , School> hash;

    while(n --){
        string id, sch;
        double grade;

        cin >>  id >> grade >> sch;
        //大小写转换
        for(auto& c : sch) c = tolower(c);

        //进行成绩转换
        if(id[0] == 'B') grade /= 1.5;
        else if(id[0] == 'T') grade *= 1.5;

        hash[sch].sum += grade;
        hash[sch].cnt ++;
        hash[sch].name =sch;
    }

    vector<School> schools;

    for ( auto item : hash){
        item.second.sum =(int)(item.second.sum + 1e-8);
        schools.push_back(item.second);
    } 

    sort(schools.begin(),schools.end());

    cout << schools.size() << endl;

    int rank =1;
    for( int i =0; i < schools.size(); i++){

        auto s = schools[i];
        // if (s.sum != schools[i - 1].sum),为了防止i=0时,i-1越界,在if条件内加 i&& 的判断
        if (i && s.sum != schools[i-1].sum) rank  = i + 1;
        printf("%d %s %d %d\n",rank, s.name.c_str(), (int)s.sum, s.cnt); 
    }

    return 0;

}

1141 PAT Ranking of Institutions (25 分)

#include <iostream>
#include <cstring>
#include <unordered_map>
#include <vector>
#include <algorithm>

using namespace std;


struct School{
    string name;
    int cnt;
    double sum;
    //默认构造
    School(): cnt(0), sum(0) {}

    bool operator< (const School &t) const{
        if (sum != t.sum ) return sum >t.sum;
        if (cnt != t.cnt) return cnt < t.cnt;
        return name < t.name;
    }
};
int main(){
    int n;
    cin >> n;
    unordered_map<string , School> hash;

    while(n --){
        string id, sch;
        double grade;

        cin >>  id >> grade >> sch;
        //大小写转换
        for(auto& c : sch) c = tolower(c);

        //进行成绩转换
        if(id[0] == 'B') grade /= 1.5;
        else if(id[0] == 'T') grade *= 1.5;

        hash[sch].sum += grade;
        hash[sch].cnt ++;
        hash[sch].name =sch;
    }

    vector<School> schools;

    for ( auto item : hash){
        item.second.sum =(int)(item.second.sum + 1e-8);
        schools.push_back(item.second);
    } 

    sort(schools.begin(),schools.end());

    cout << schools.size() << endl;

    int rank =1;
    for( int i =0; i < schools.size(); i++){

        auto s = schools[i];
        // if (s.sum != schools[i - 1].sum),为了防止i=0时,i-1越界,在if条件内加 i&& 的判断
        if (i && s.sum != schools[i-1].sum) rank  = i + 1;
        printf("%d %s %d %d\n",rank, s.name.c_str(), (int)s.sum, s.cnt); 
    }

    return 0;

}

1153 Decode Registration Card of PAT (25 分)

1 字符串处理
1001 A+B Format (20 分)
Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input:
-1000000 9结尾无空行
Sample Output:
-999,991


toString () 方法用于返回以一个字符串表示的 Number 对象值。 (可以正常转换正负号

#include <iostream>

using namespace std;

int main()
{
    int a,b;
    cin >> a>> b;
    int c= a+b;
    string num = to_string(c);
    string res;
    for(int i = num.size()-1,j =0; i >=0;i--)
    {
        res =num[i]+res;
        ++j;
        if(j % 3 ==0 && i && num[i-1] != '-') res= ',' +res;
    }

    cout <<res <<endl;
}

1005 Spell It Right (20 分)
Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.
Input Specification:
Each input file contains one test case. Each case occupies one line which contains an N (≤10100).
Output Specification:
For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.
Sample Input:
12345结尾无空行
Sample Output:
one five结尾无空行

Code
通过先读入字符串,然后利用for(auto c:num)遍历字符串的每一个数字,`c -‘0’来把字符转换为int类型的数字

数字和英文转换用if-else也可以写,但是太麻烦
定义char类型数组
char word[10][10]= { "zero","one","two","three","four", "five","six","seven","eight","nine",};
来和0 1 2 ··· 一一对应
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main()
{
    string num;
    cin >>num;

    int sum= 0;
    for( auto c:num ) sum += c-'0';

    char word[10][10] ={"zero","one","two","three","four","five","six","seven","eight","nine"};
    string str=to_string(sum);
    cout<<word[str[0]-'0'];
    for(int i = 1; i < str.size();i++) cout << ' ' << word[str[i]-'0'];

    return 0;
}
1006 Sign In and Sign Out (25 分)
At the beginning of every day, the first person who signs in the computer room will unlock the door, and the last one who signs out will lock the door. Given the records of signing in's and out's, you are supposed to find the ones who have unlocked and locked the door on that day.
Input Specification:
Each input file contains one test case. Each case contains the records for one day. The case starts with a positive integer M, which is the total number of records, followed by M lines, each in the format:
ID_number Sign_in_time Sign_out_time
where times are given in the format HH:MM:SS, and ID_number is a string with no more than 15 characters.
Output Specification:
For each test case, output in one line the ID numbers of the persons who have unlocked and locked the door on that day. The two ID numbers must be separated by one space.
Note: It is guaranteed that the records are consistent. That is, the sign in time must be earlier than the sign out time for each person, and there are no two persons sign in or out at the same moment.
Sample Input:
3 CS301111 15:30:28 17:00:10 SC3021234 08:00:00 11:25:25 CS301133 21:45:00 21:58:40结尾无空行
Sample Output:
SC3021234 CS301133结尾无空行
时间可以直接用字典序比较,这种格式可以直接读入string

if(!i || in_time<open_time)一定要有 !i的条件,确保i=0的时候先进行赋值比较,不然的话会一直没有值读入进去
#include <iostream>


using namespace std;
int main()
{
    string open_id, open_time;
    string close_id, close_time;

    int m;

    cin >>m;
    for(int i =0; i <m; i++)
    {
        string id, in_time,out_time;
        cin>> id >>in_time>>out_time;
        //更新开门人
        if(!i || in_time<open_time)
        {
            open_id =id;
            open_time=in_time;
        }
        //更新锁门人
        if(!i || out_time >close_time)
        {
            close_id= id;
            close_time=out_time;
        }
    }
    cout << open_id<< ' ' <<close_id;
}
1035 Password (20 分)
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 0<N<100, the number of nodes in a tree, and M (<N), the number of non-leaf nodes. Then M lines follow, each in the format:
ID K ID[1] ID[2] ... ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.
The input ends with N being 0. That case must NOT be processed.
Output Specification:
For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.
The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output 0 1 in a line.
Sample Input:
2 1 01 1 02结尾无空行
Sample Output:
0 1结尾无空行
pta代码未完成

#include <iostream>

using namespace std;
const int N =1010;
string name[N],pwd[N];
string change(string str)
{
    string res;
    for(auto c:str){
        if(c=='1') res +='@';
        else if( c== '0') res+='%';
        else if( c=='l') res+='L';
        else if(c=='O') res +='o';
        else res +=c;
    }
    return res;
}
int main(){
    int n;
    cin >>n;
    int m=0;

    for(int i =0; i< n; i++){
        string cur_name,cur_pwd;
        cin >> cur_name>> cur_pwd;
        string changed_pwd;
        changed_pwd= change(cur_pwd);
        if(changed_pwd  != cur_pwd)
        {

            name[m]=cur_name;
            pwd[m]=changed_pwd;
            m ++;
        }
    }
    if(!m){
        if(n ==1) printf("There is 1 account and no account is modified");
        else printf("There are %d accounts and no account is modified",n);
    }else{
        cout<<m<<endl;
        for(int i =0; i<m;i++){
            cout << name[i]<< ' '<<pwd[i]<< endl;
            }
     }

}
1036 Boys vs Girls (25 分)

This time you are asked to tell the difference between the lowest grade of all the male students and the highest grade of all the female students.
Input Specification:
Each input file contains one test case. Each case contains a positive integer N, followed by N lines of student information. Each line contains a student's name, gender, ID and grade, separated by a space, where name and ID are strings of no more than 10 characters with no space, gender is either F (female) or M (male), and grade is an integer between 0 and 100. It is guaranteed that all the grades are distinct.
Output Specification:
For each test case, output in 3 lines. The first line gives the name and ID of the female student with the highest grade, and the second line gives that of the male student with the lowest grade. The third line gives the difference gradeF−gradeM. If one such kind of student is missing, output Absent in the corresponding line, and output NA in the third line instead.
Sample Input 1:
3 Joe M Math990112 89 Mike M CS991301 100 Mary F EE990830 95结尾无空行
Sample Output 1:
Mary EE990830 Joe Math990112 6
结尾无空行
Sample Input 2:
1 Jean M AA980920 60
结尾无空行
Sample Output 2:
Absent Jean AA980920 NA
结尾无空行


#include <iostream>
using namespace std;
int main(){
    int n;
    cin >>n;
    string boy_name,boy_id;
    int boy_score;
    string girl_name,girl_id;
    int girl_score;

    for(int i =0; i<n;i++){
        string name,id,sex;
        int score;
        cin >>name>> sex>>id>>score;
        if(sex == "M"){
            if(boy_id.empty() || score< boy_score){
                boy_score=score;
                boy_name=name;
                boy_id=id;
            }
        }else{
            if(girl_id.empty() || score> girl_score){
                girl_score=score;
                girl_name=name;
                girl_id=id;
            }

        }
    }

    if(girl_id.empty()) puts("Absent");
    else cout <<girl_name<< ' '<<girl_id<<endl;
    if(boy_id.empty()) puts("Absent");
    else cout <<boy_name<< ' '<<boy_id<<endl;
    if(!girl_id.empty() && !boy_id.empty()) cout << girl_score-boy_score;
    else puts("NA");
}
girl_id.empty()可以方便判断这个值是不是为空,

1050 String Subtraction (20 分)

Given two strings S1 and S2, S=S1−S2 is defined to be the remaining string after taking all the characters in S2 from S1. Your task is simply to calculate S1−S2 for any given strings. However, it might not be that simple to do it fast.
Input Specification:
Each input file contains one test case. Each case consists of two lines which gives S1 and S2, respectively. The string lengths of both strings are no more than 104. It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.
Output Specification:
For each test case, print S1−S2 in one line.
Sample Input:
They are students. aeiou结尾无空行
Sample Output:
Thy r stdnts.结尾无空行
#include <iostream>
#include <unordered_set>

using namespace std;
string s1,s2;
int main(){
    getline(cin,s1);
    getline(cin,s2);

    unordered_set<char> hash;//定义char类型哈希表
    for(auto c:s2) hash.insert(c);// 把s1字符压入哈希表
    string res;

    for(auto c:s1){
        if(!hash.count(c)) res+=c;//返回c出现的数量,如果为0执行res+=c
    }
    cout << res<< endl;

}
#include <unordered_set>哈希表头文件
unordered_set<char> hash;定义char类型哈希表
for(auto c:s2) hash.insert(c);把s1字符压入哈希表
hash.count(c)返回哈希表中c出现的数量


1071 Speech Patterns (25 分)

People often have a preference among synonyms of the same word. For example, some may prefer "the police", while others may prefer "the cops". Analyzing such patterns can help to narrow down a speaker's identity, which is useful when validating, for example, whether it's still the same person behind an online avatar.
Now given a paragraph of text sampled from someone's speech, can you find the person's most commonly used word?
Input Specification:
Each input file contains one test case. For each case, there is one line of text no more than 1048576 characters in length, terminated by a carriage return \n. The input contains at least one alphanumerical character, i.e., one character from the set [0-9 A-Z a-z].
Output Specification:
For each test case, print in one line the most commonly occurring word in the input text, followed by a space and the number of times it has occurred in the input. If there are more than one such words, print the lexicographically smallest one. The word should be printed in all lower case. Here a "word" is defined as a continuous sequence of alphanumerical characters separated by non-alphanumerical characters or the line beginning/end.
Note that words are case insensitive.
Sample Input:
Can1: "Can a can can a can?  It can!"结尾无空行
Sample Output:
can 5结尾无空行
#include <iostream>
#include <unordered_map>//哈希map

using namespace std;


//judge whether the char belong to letter or number
bool check(char c){
    if(c >='0' && c<='9') return true;
    if(c >='a' && c<='z') return true;
    if(c >='A' && c<='Z') return true;
    return false;
}

int main(){
    string str;
    getline(cin,str);//cin the whole line including spaces

    unordered_map<string,int> hash;//create a hash map
    //i j dual pointer
    for(int i =0; i<str.size();i++){
        if(check(str[i])){
            string word;
            int j =i;
            while(j <str.size() && check(str[j])){
                word+=tolower(str[j]);//change the upper letter to the lower letter
                j++;
            }
            hash[word] ++;//put the word into the hash
            i =j;//after the word is finish,start the new i at the last j location
        }
    }

    string word;
    int cnt=-1;//makesure that item.second >cnt
    for(auto item:hash)
        if(item.second>cnt||(item.second ==cnt && item.first < word)){
            word=item.first;
            cnt=item.second;
        }


    cout << word<<' '<< cnt<<endl;
}
利用hash map

利用双指针
判断是否是字母大小写或者数字单独用一个函数
1061 Dating (20 分)
Sherlock Holmes received a note with some strange strings: Let's date! 3485djDkxh4hhGE 2984akDfkkkkggEdsb s&hgsfdk d&Hyscvnm. It took him only a minute to figure out that those strange strings are actually referring to the coded time Thursday 14:04 -- since the first common capital English letter (case sensitive) shared by the first two strings is the 4th capital letter D, representing the 4th day in a week; the second common character is the 5th capital letter E, representing the 14th hour (hence the hours from 0 to 23 in a day are represented by the numbers from 0 to 9 and the capital letters from A to N, respectively); and the English letter shared by the last two strings is s at the 4th position, representing the 4th minute. Now given two pairs of strings, you are supposed to help Sherlock decode the dating time.
Input Specification:
Each input file contains one test case. Each case gives 4 non-empty strings of no more than 60 characters without white space in 4 lines.
Output Specification:
For each test case, print the decoded time in one line, in the format DAY HH:MM, where DAY is a 3-character abbreviation for the days in a week -- that is, MON for Monday, TUE for Tuesday, WED for Wednesday, THU for Thursday, FRI for Friday, SAT for Saturday, and SUN for Sunday. It is guaranteed that the result is unique for each case.
Sample Input:
3485djDkxh4hhGE  2984akDfkkkkggEdsb  s&hgsfdk  d&Hyscvnm结尾无空行
Sample Output:
THU 14:04结尾无空行
#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    string a,b,c,d;
    cin>>a>>b>>c>>d;

    int k=0;
    while(true){
        if(a[k]==b[k] && a[k] >='A' && a[k]<='G') break;
        k++;
    }

    char weekdays[7][4] ={"MON","TUE","WES","THU","FRI","SAT","SUN"};
    printf("%s",weekdays[a[k]-'A']);

    k++;
    while(true)
    {
        if(a[k]==b[k] && (a[k]>='0' && a[k]<='9' || a[k] >='A' && a[k] <= 'N')) break;
        k++;
    }
    printf("%02d:",a[k] <='9' ? a[k]-'0' : a[k]-'A'+10);

    for(int i =0;;i++)
        if(c[i] ==d[i] && (c[i]>='a' && c[i] >='z' || c[i] >='A' && c[i] <='Z'))
        {
            printf("%02d\n",i);
            break;
        }
    return 0;
}
这种不考虑没有结果,只用break的情况,如果超时,首先排除是不是判断写的有问题

1016 Phone Bills (25 分)
A long-distance telephone company charges its customers by the following rules:
Making a long-distance call costs a certain amount per minute, depending on the time of day when the call is made. When a customer starts connecting a long-distance call, the time will be recorded, and so will be the time when the customer hangs up the phone. Every calendar month, a bill is sent to the customer for each minute called (at a rate determined by the time of day). Your job is to prepare the bills for each month, given a set of phone call records.
Input Specification:
Each input file contains one test case. Each case has two parts: the rate structure, and the phone call records.
The rate structure consists of a line with 24 non-negative integers denoting the toll (cents/minute) from 00:00 - 01:00, the toll from 01:00 - 02:00, and so on for each hour in the day.
The next line contains a positive number N (≤1000), followed by N lines of records. Each phone call record consists of the name of the customer (string of up to 20 characters without space), the time and date (MM:dd:HH:mm), and the word on-line or off-line.
For each test case, all dates will be within a single month. Each on-line record is paired with the chronologically next record for the same customer provided it is an off-line record. Any on-line records that are not paired with an off-line record are ignored, as are off-line records not paired with an on-line record. It is guaranteed that at least one call is well paired in the input. You may assume that no two records for the same customer have the same time. Times are recorded using a 24-hour clock.
Output Specification:
For each test case, you must print a phone bill for each customer.
Bills must be printed in alphabetical order of customers' names. For each customer, first print in a line the name of the customer and the month of the bill in the format shown by the sample. Then for each time period of a call, print in one line the beginning and ending time and date (dd:HH:mm), the lasting time (in minute) and the charge of the call. The calls must be listed in chronological order. Finally, print the total charge for the month in the format shown by the sample.
Sample Input:
10 10 10 10 10 10 20 20 20 15 15 15 15 15 15 15 20 30 20 15 15 10 10 10 10 CYLL 01:01:06:01 on-line CYLL 01:28:16:05 off-line CYJJ 01:01:07:00 off-line CYLL 01:01:08:03 off-line CYJJ 01:01:05:59 on-line aaa 01:01:01:03 on-line aaa 01:02:00:01 on-line CYLL 01:28:15:41 on-line aaa 01:05:02:24 on-line aaa 01:04:23:59 off-line结尾无空行
Sample Output:
CYJJ 01 01:05:59 01:07:00 61 $12.10 Total amount: $12.10 CYLL 01 01:06:01 01:08:03 122 $24.40 28:15:41 28:16:05 24 $3.85 Total amount: $28.25 aaa 01 02:00:01 04:23:59 4318 $638.80 Total amount: $638.80结尾无空行

#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 10010;
const int M = 31 * 1440 +10;
int n;
int cost[24];
double sum[M];

struct Record{
    int minutes;
    string state;
    string format_time;

    bool operator< (const Record& t) const{
        return minutes < t.minutes;
    }

};

map<string, vector<Record>> persons;


int main(){
    for ( int i =0; i < 24; i ++ ) cin >> cost[i];
    for ( int i =0; i < M; i ++ ) sum[i] = sum[i-1] + cost[(i-1) % 1440 / 60 ]/100.0;
    cin >> n;
    char name[25],state[10],format_time[20];
    int month, day, hour, minute;


    for(int i = 0; i < n; i++)
    {
        scanf("%s %d:%d:%d:%d %s", name, &month, &day, &hour, &minute, state);
        sprintf(format_time, "%02d:%02d:%02d", day, hour, minute);

        int minutes  = (day-1) *1440 + hour *60 + minute;
        persons[name].push_back({minutes,state,format_time});
    }

    for (auto &person : persons){
        auto name = person.first;
        auto records = person.second;
        sort(records.begin(), records.end());

        double total = 0;
        for (int i =0; i + 1 < records.size(); i ++ ){
            auto a = records[i], b = records[i + 1];
            if(a.state == "on-line" && b.state == "off-line"){
                if(!total) printf("%s %02d\n", name.c_str(), month);
                cout << a.format_time << ' ' << b.format_time;

                double c = sum[b.minutes] - sum[a.minutes];
                printf(" %d $%.2lf\n", b.minutes - a.minutes, c);
                total +=c;

            }
        }
        if(total) printf("Total amount: $%.2lf\n",total);
    }
    return 0;
}
代码量一大,容易出bug
注意掉包和对map的理解

1017 Queueing at Bank (25 分)

Suppose a bank has K windows open for service. There is a yellow line in front of the windows which devides the waiting area into two parts. All the customers have to wait in line behind the yellow line, until it is his/her turn to be served and there is a window available. It is assumed that no window can be occupied by a single customer for more than 1 hour.
Now given the arriving time T and the processing time P of each customer, you are supposed to tell the average waiting time of all the customers.
Input Specification:
Each input file contains one test case. For each case, the first line contains 2 numbers: N (≤104) - the total number of customers, and K (≤100) - the number of windows. Then N lines follow, each contains 2 times: HH:MM:SS - the arriving time, and P - the processing time in minutes of a customer. Here HH is in the range [00, 23], MM and SS are both in [00, 59]. It is assumed that no two customers arrives at the same time.
Notice that the bank opens from 08:00 to 17:00. Anyone arrives early will have to wait in line till 08:00, and anyone comes too late (at or after 17:00:01) will not be served nor counted into the average.
Output Specification:
For each test case, print in one line the average waiting time of all the customers, in minutes and accurate up to 1 decimal place.
Sample Input:
7 3 07:55:00 16 17:00:01 2 07:59:59 15 08:01:00 60 08:00:00 30 08:00:02 2 08:03:00 10结尾无空行
Sample Output:
8.2结尾无空行
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <vector>

using namespace std;

const int N = 1010;
int n,m;

struct Person{
    int arrive_time;
    int service_time;

    bool operator< (const Person& t) const{
        return arrive_time < t.arrive_time;
    }
}persons[N];

int main(){
    cin >> n >> m;
    for ( int i = 0; i < n; i ++){
        int hour, minute, second, service_time;
        scanf("%d:%d:%d %d", &hour, &minute, &second, &service_time);

        service_time = min(service_time, 60);

        persons[i] = {hour * 3600 + minute * 60 + second, service_time * 60};
    }

    priority_queue<int, vector<int>, greater<int>> windows;

    for (int i =0; i < m; i ++) windows.push( 8 * 3600);
    sort(persons, persons + n);
    int sum =0, cnt =0;
    for( int i =0 ; i < n; i ++){
        auto person = persons[i];
        if (person.arrive_time > 17 * 3600) break;
        int w =windows.top();
        windows.pop();

        //printf("%d %d\n",person.arrive_time, w);
        int start_time = max(person.arrive_time, w);
        sum += start_time - person.arrive_time;
        cnt ++;
        windows.push(start_time+person.service_time);

    }
    printf("%.1lf\n",(double)sum /cnt /60);


    return 0;


}
1073 Scientific Notation (20 分)



#include <iostream>
#include <string>
using namespace std;

int main(){
    string s;
    cin >> s;
    if(s[0] =='-') cout << "-";
    int k = s.find("E");

    string a = s[1] + s.substr(3, k-3);
    //cout <<a;
    int b = stoi(s.substr(k+1));
    //cout <<b<<endl;
    b++;
    if(b <=0)  a = "0." +string(-b, '0') + a;
    else if( b >=s.size()) a = a + string(b-a.size(),'0');
    else a =a.substr(0,b) + '.' + a.substr(b);

    cout << a;
}
1077 Kuchiguse (20 分)

#include <iostream>

using namespace std;

const int N = 110;

int n;

string s[N];

int main(){
    cin >> n;
    getchar();//    把回车读取, 再读取每一行
    for (int i =0; i< n; i ++){
        getline(cin,s[i]);
    }
//    后缀长度为 s[0]长度
//    后缀长度为 s[0]长度-1
//    ... 直到sf.size() == s[0].size() 暴力枚举每一种可能的公共后缀

    for (int k = s[0].size(); k ; k--){

        string sf = s[0].substr(s[0].size() - k);//取后缀

        bool is_matched =true;//标记后缀是否相等

        //遍历每一行
        for (int i =1; i < n; i ++){
            //当sf后缀大于s[i]长度或者
            if(k > s[i].size() || s[i].substr(s[i].size()-k) != sf){
                is_matched = false;
                break;
            }
        }

        if(is_matched){
            cout << sf << endl;

            return 0;
        }
    }

    puts("nai");

    return 0;
}



1084 Broken Keyboard (20 分)
#include <iostream>

using namespace std;
//定义一个判断数组,用于判断某一个字符是否已经被发现键盘损坏输出过了,200是确定大于ascii的值,所有定在200
bool st[200] = {0};

int main(){
    string a,b;
    cin >> a >> b;
    for( int i =0, j =0; i < a.size(); i++){
        char x=toupper(a[i]), y = toupper(b[j]);//统一转换为大写

        //双指针,如果x=y,指针一起向后移
        if( x == y) j++;
        else if( !st[x]) cout << x, st[x] =1;
    }

    return 0;
}

try =catch 语句    


#include <iostream>

using namespace std;

int main(){
    int n;
    cin >> n;
    int cnt = 0;
    double sum = 0;
    while(n--){
        string num;
        cin >> num;
        double x;

        bool success = true;
        try{
            size_t idx;
            x =stof(num, &idx);

            if(idx < num.size()) success = false;
        }catch(...){
            success = false;
        }
        //判断大小是否在范围内
        if( x < -1000 || x > 1000) success = false;

        //判断小数点是不是后两位
        int k = num.find('.');
        if( k != -1 && (num.size() - k) > 3) success = false;

        if (success) cnt ++, sum+=x;
        else printf("ERROR: %s is not a legal number\n",num.c_str());


    }

    if( cnt > 1) printf("The average of %d numbers is %.2lf",cnt, sum /cnt);
    else if (cnt ==1) printf("The average of 1 number is %.2lf",sum);
    else printf("The average of 0 numbers is Undefined");
}
#include <iostream>
#include <unordered_set>

using namespace std;

const int N = 1010;

int m, n,s;
string name[N];

int main(){
    cin >> m >> n >> s;
    for (int i =1 ; i <= m; i ++) cin >> name[i];
    unordered_set<string> hash;

    int k = s;
    while( k <= m){
        if(hash.count(name[k])) k ++;
        else{
            cout << name[k] << endl;
            hash.insert(name[k]);
            k +=n;
        }
    }

    if(hash.empty()) puts("Keep going...");
    return 0;
}
#include <iostream>
#include <cstring>
#include <unordered_map>
#include <vector>
#include <algorithm>

using namespace std;


struct School{
    string name;
    int cnt;
    double sum;
    //默认构造
    School(): cnt(0), sum(0) {}

    bool operator< (const School &t) const{
        if (sum != t.sum ) return sum >t.sum;
        if (cnt != t.cnt) return cnt < t.cnt;
        return name < t.name;
    }
};
int main(){
    int n;
    cin >> n;
    unordered_map<string , School> hash;

    while(n --){
        string id, sch;
        double grade;

        cin >>  id >> grade >> sch;
        //大小写转换
        for(auto& c : sch) c = tolower(c);

        //进行成绩转换
        if(id[0] == 'B') grade /= 1.5;
        else if(id[0] == 'T') grade *= 1.5;

        hash[sch].sum += grade;
        hash[sch].cnt ++;
        hash[sch].name =sch;
    }

    vector<School> schools;

    for ( auto item : hash){
        item.second.sum =(int)(item.second.sum + 1e-8);
        schools.push_back(item.second);
    } 

    sort(schools.begin(),schools.end());

    cout << schools.size() << endl;

    int rank =1;
    for( int i =0; i < schools.size(); i++){

        auto s = schools[i];
        // if (s.sum != schools[i - 1].sum),为了防止i=0时,i-1越界,在if条件内加 i&& 的判断
        if (i && s.sum != schools[i-1].sum) rank  = i + 1;
        printf("%d %s %d %d\n",rank, s.name.c_str(), (int)s.sum, s.cnt); 
    }

    return 0;

}




1141 PAT Ranking of Institutions (25 分)
#include <iostream>
#include <cstring>
#include <unordered_map>
#include <vector>
#include <algorithm>

using namespace std;


struct School{
    string name;
    int cnt;
    double sum;
    //默认构造
    School(): cnt(0), sum(0) {}

    bool operator< (const School &t) const{
        if (sum != t.sum ) return sum >t.sum;
        if (cnt != t.cnt) return cnt < t.cnt;
        return name < t.name;
    }
};
int main(){
    int n;
    cin >> n;
    unordered_map<string , School> hash;

    while(n --){
        string id, sch;
        double grade;

        cin >>  id >> grade >> sch;
        //大小写转换
        for(auto& c : sch) c = tolower(c);

        //进行成绩转换
        if(id[0] == 'B') grade /= 1.5;
        else if(id[0] == 'T') grade *= 1.5;

        hash[sch].sum += grade;
        hash[sch].cnt ++;
        hash[sch].name =sch;
    }

    vector<School> schools;

    for ( auto item : hash){
        item.second.sum =(int)(item.second.sum + 1e-8);
        schools.push_back(item.second);
    } 

    sort(schools.begin(),schools.end());

    cout << schools.size() << endl;

    int rank =1;
    for( int i =0; i < schools.size(); i++){

        auto s = schools[i];
        // if (s.sum != schools[i - 1].sum),为了防止i=0时,i-1越界,在if条件内加 i&& 的判断
        if (i && s.sum != schools[i-1].sum) rank  = i + 1;
        printf("%d %s %d %d\n",rank, s.name.c_str(), (int)s.sum, s.cnt); 
    }

    return 0;

}


1153 Decode Registration Card of PAT (25 分)
#include <iostream>
#include <cstring>
#include <unordered_map>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 10010;

int n, m;

//定义person结构体
struct Person{
    string id;
    int grade;
    //分数降序,id字典序升序
    bool operator< (const Person &t) const{
        if (grade != t.grade) return grade >t.grade;
        return id <t.id;
    }
}p[N];

int main(){
    cin >> n >> m;
    //所有id 和grade先读入p[N]
    for(int i =0; i < n; i ++) cin >>p[i].id >>p[i].grade;
    for(int k =1; k <= m; k ++){
        string t,c;
        cin >> t >> c;

        printf("Case %d: %s %s\n",k , t.c_str() ,c.c_str());
        if (t[0] == '1') {
            vector<Person> persons;
            for( int i = 0 ; i < n ; i ++){
                //入栈
                if(p[i].id[0] ==c[0]) persons.push_back(p[i]);
            }

            sort(persons.begin(),persons.end());
            if(persons.empty()) puts("NA");
            else{
                for(auto person : persons) printf("%s %d\n",person.id.c_str(),person.grade);
            }

        }else if (t[0] == '2'){
            int cnt = 0, sum =0;
            for(int i =0 ; i < n; i ++){
                if(p[i].id.substr(1,3) ==c){
                    cnt ++;
                    sum +=p[i].grade;
                }
            }
            if (!cnt) puts("NA");
            else printf("%d %d\n",cnt ,sum);
        }else{
            unordered_map<string, int> hash;
            for (int i = 0; i < n; i ++){
                if (p[i].id.substr(4, 6) == c){
                    hash[p[i].id.substr(1, 3)] ++;
                }

            }

            //pair
            vector<pair<int, string >> rooms;
            for(auto item : hash) rooms.push_back({-item.second, item.first});

            sort(rooms.begin(), rooms.end());
            if (rooms.empty()) puts("NA");
            else {
                for (auto room : rooms){
                    printf("%s %d\n",room.second.c_str(), -room.first);
                }
            }
        }
    }

    return 0;
}#include <iostream>
#include <cstring>
#include <unordered_map>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 10010;

int n, m;

//定义person结构体
struct Person{
    string id;
    int grade;
    //分数降序,id字典序升序
    bool operator< (const Person &t) const{
        if (grade != t.grade) return grade >t.grade;
        return id <t.id;
    }
}p[N];

int main(){
    cin >> n >> m;
    //所有id 和grade先读入p[N]
    for(int i =0; i < n; i ++) cin >>p[i].id >>p[i].grade;
    for(int k =1; k <= m; k ++){
        string t,c;
        cin >> t >> c;

        printf("Case %d: %s %s\n",k , t.c_str() ,c.c_str());
        if (t[0] == '1') {
            vector<Person> persons;
            for( int i = 0 ; i < n ; i ++){
                //入栈
                if(p[i].id[0] ==c[0]) persons.push_back(p[i]);
            }

            sort(persons.begin(),persons.end());
            if(persons.empty()) puts("NA");
            else{
                for(auto person : persons) printf("%s %d\n",person.id.c_str(),person.grade);
            }

        }else if (t[0] == '2'){
            int cnt = 0, sum =0;
            for(int i =0 ; i < n; i ++){
                if(p[i].id.substr(1,3) ==c){
                    cnt ++;
                    sum +=p[i].grade;
                }
            }
            if (!cnt) puts("NA");
            else printf("%d %d\n",cnt ,sum);
        }else{
            unordered_map<string, int> hash;
            for (int i = 0; i < n; i ++){
                if (p[i].id.substr(4, 6) == c){
                    hash[p[i].id.substr(1, 3)] ++;
                }

            }

            //pair
            vector<pair<int, string >> rooms;
            for(auto item : hash) rooms.push_back({-item.second, item.first});

            sort(rooms.begin(), rooms.end());
            if (rooms.empty()) puts("NA");
            else {
                for (auto room : rooms){
                    printf("%s %d\n",room.second.c_str(), -room.first);
                }
            }
        }
    }

    return 0;
}