华为机考108题(c++)(17-22)

HJ17 坐标移动

描述

开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。

输入:

合法坐标为A(或者D或者W或者S) + 数字(两位以内)

坐标之间以;分隔。

非法坐标点需要进行丢弃。如AA10;  A1A;  $%$;  YAD; 等。

下面是一个简单的例子 如:

A10;S20;W10;D30;X;A1A;B10A11;;A10;

处理过程:

起点(0,0)

+   A10   =  (-10,0)

+   S20   =  (-10,-20)

+   W10  =  (-10,-10)

+   D30  =  (20,-10)

+   x    =  无效

+   A1A   =  无效

+   B10A11   =  无效

+  一个空 不影响

+   A10  =  (10,-10)

结果 (10, -10)

数据范围:每组输入的字符串长度满足1≤n≤10000  ,坐标保证满足 −2^31≤x,y≤23^1−1  ,且数字部分仅含正数

输入描述:

一行字符串

输出描述:

最终坐标,以逗号分隔

#include 
#include 
#include 
using namespace std;

/* check if a cmd is valid */
bool isValid(string const& cmd);
/* change x and y according to cmd */
void move(string const& cmd, int& x, int& y);

/* MAIN FUNC */
int main() {
    int x = 0, y = 0;
    string cmds, cmd = "";
    getline(cin, cmds, '\n');
    
    for (auto s: cmds) {
        if (s == ';') {
            if (isValid(cmd)) {move(cmd, x, y);}
            cmd = "";
        }
        else {cmd += s;}
    }
    cout << x << "," << y;
    return 0;
}

bool isValid(string const& cmd) {
    if (cmd.length() <= 1) {return false;}
    if (!isalpha(cmd[0])) {return false;}
    for (size_t i = 1; i < cmd.length(); ++i) {
        if (!isdigit(cmd[i])) {return false;}
    }
    return true;
}

void move(string const& cmd, int& x, int& y) {
    int num = stoi(cmd.substr(1));
    switch(cmd[0]) {
        case 'W': y += num; break;
        case 'S': y -= num; break;
        case 'D': x += num; break;
        case 'A': x -= num; break;
    }
}

HJ18 识别有效的IP地址和掩码并进行分类统计

描述

请解析IP地址和对应的掩码,进行分类识别。要求按照A/B/C/D/E类地址归类,不合法的地址和掩码单独归类。

所有的IP地址划分为 A,B,C,D,E五类

A类地址从1.0.0.0到126.255.255.255;

B类地址从128.0.0.0到191.255.255.255;

C类地址从192.0.0.0到223.255.255.255;

D类地址从224.0.0.0到239.255.255.255;

E类地址从240.0.0.0到255.255.255.255

私网IP范围是:

从10.0.0.0到10.255.255.255

从172.16.0.0到172.31.255.255

从192.168.0.0到192.168.255.255

子网掩码为二进制下前面是连续的1,然后全是0。(例如:255.255.255.32就是一个非法的掩码)

(注意二进制下全是1或者全是0均为非法子网掩码)

注意:

1. 类似于【0.*.*.*】和【127.*.*.*】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略

2. 私有IP地址和A,B,C,D,E类地址是不冲突的

输入描述:

多行字符串。每行一个IP地址和掩码,用~隔开。

请参考帖子https://www.nowcoder.com/discuss/276处理循环输入的问题。

输出描述:

统计A、B、C、D、E、错误IP地址或错误掩码、私有IP的个数,之间以空格隔开。

方法一:遍历检查

华为机考108题(c++)(17-22)_第1张图片

#include
#include
#include
using namespace std;

int main(){
    vector arr(7, 0); //分别对应题目的7个类别
    string s;
    while(getline(cin, s)){
        int n = s.length();
        vector ips; //记录ip地址的数字
        bool bad = false;
        bool isnum = false;
        int num = 0;
        for(int i = 0; i < n; i++){ //遍历该ip字符串
            if(s[i] == '.' || s[i] == '~'){ //以.或者~分割
                if(isnum){
                    if(num > 255){
                        bad = true; //错误ip,数字不能超过255
                        break;
                    }
                    ips.push_back(num);
                    isnum = false;
                    num = 0;
                }else{
                    arr[5]++; //错误地址
                    bad = true;
                    break;
                }
            }else if(s[i] >= '0' && s[i] <= '9'){
                isnum = true;
                num = num * 10 + s[i] - '0'; //计算数字
            }else{
                arr[5]++;
                isnum = false; //错误地址,数字部分还有非数字
                bad = true;
                break;
            }
        }
        if(isnum)
            ips.push_back(num); //最后一个数字
        if(ips[0] == 0 || ips[0] == 127 || bad) 
            continue; //忽略0或者127开头的地址,错误ip已经统计了过了,可以忽略
        int mask = 4; //查看掩码的数字
        while(mask < 8 && ips[mask] == 255)
            mask++;  //找到掩码第一个不全为1的数
        if(mask == 8){ //掩码全1也是不合法
            arr[5]++;
            continue; 
        }else if(ips[mask] == 254 || ips[mask] == 252 || ips[mask] == 248 || ips[mask] == 240 || ips[mask] == 224 || ips[mask] == 191 || ips[mask] == 128)
            mask++; //各类掩码含1的最后一位
        while(mask < 8 && ips[mask] == 0)
            mask++;
        if(mask != 8){ //掩码后半部分不能有1
            arr[5]++;
            continue;
        }
        if(ips[0] >= 1 && ips[0] <= 126)
            arr[0]++; //A类地址
        else if(ips[0] >= 128 && ips[0] <= 191) 
            arr[1]++; //B类地址
        else if(ips[0] >= 192 && ips[0] <= 223) 
            arr[2]++; //C类地址
        else if(ips[0] >= 224 && ips[0] <= 239) 
            arr[3]++; //D类地址
        else if(ips[0] >= 240 && ips[0] <= 255) 
            arr[4]++; //E类地址
        if(ips[0] == 10) 
            arr[6]++; //私有地址10开头的
        else if(ips[0] == 172 && (ips[1] >= 16 && ips[1] <= 31)) 
            arr[6]++; //私有地址172.16.0.0-172.31.255.255
        else if(ips[0] == 192 && ips[1] == 168) 
            arr[6]++; //私有地址192.168.0.0-192.168.255.255
    }
    for(int i = 0; i < 7; i++){ //输出
        cout << arr[i];
        if(i != 6)
           cout << " ";
    }
    cout << endl;
    return 0;
}

方法二:正则表达式

import re
#各类的地址的正则表达式
error_pattern = re.compile(r'1+0+')
A_pattern = re.compile(r'((12[0-6]|1[0-1]\d|[1-9]\d|[1-9])\.)((1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)')
B_pattern = re.compile(r'(12[8-9]|1[3-8]\d|19[0-1])\.((1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)')
C_pattern = re.compile(r'(19[2-9]|2[0-1]\d|22[0-3])\.((1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)')
D_pattern = re.compile(r'(22[4-9]|23\d)\.((1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)')
E_pattern = re.compile(r'(24\d|25[0-5])\.((1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)')
self_pattern = re.compile(r'((10\.((1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d))|(172\.(1[6-9]|2\d|3[0-1])\.(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d))|(192\.168\.(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)))')
escape = re.compile(r'((0|127)\.((1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d))')

def judge_mask(line):
    if line == '255.255.255.255' or line == '0.0.0.0': #全0全1
        return 0
    judge = line.split('.') #按照点分割数字
    res = ''
    for j in judge:
        res += '{:0>8b}'.format(int(j))
    res = re.fullmatch(error_pattern, res)
    if res == None:
        return 0
    else:
        return 1

def judge(pattern, line): #匹配函数
    if re.fullmatch(pattern, line) != None:
        return 1
    else:
        return 0

arr = [0]*7
while True:
    try:
        line = input().split('~') #从~分割IP地址和掩码
        if line[0][0:4] == "127." or line[0][0:2] == "0.":  #优先判断127或者0开头的
            continue
        if judge_mask(line[1]): #先判断掩码是否正确
            #正则比较各个IP地址
            if judge(self_pattern, line[0]): #私有与其他的不冲突,优先单独匹配
                arr[6] += 1
            if judge(A_pattern, line[0]):
                arr[0] += 1
            elif judge(B_pattern, line[0]): 
                arr[1] += 1
            elif judge(C_pattern, line[0]):
                arr[2] += 1
            elif judge(D_pattern, line[0]):
                arr[3] += 1
            elif judge(E_pattern, line[0]):
                arr[4] += 1
            elif judge(escape, line[0]):
                continue
            else:
                arr[5] += 1 #IP地址错误
        else: #掩码错误
            arr[5] += 1
    except:
        print(' '.join([str(i) for i in arr])) #输出
        break

HJ19 简单错误记录

描述

开发一个简单错误记录功能小模块,能够记录出错的代码所在的文件名称和行号。

处理:

1、 记录最多8条错误记录,循环记录,最后只用输出最后出现的八条错误记录。对相同的错误记录只记录一条,但是错误计数增加。最后一个斜杠后面的带后缀名的部分(保留最后16位)和行号完全匹配的记录才做算是相同的错误记录。

2、 超过16个字符的文件名称,只记录文件的最后有效16个字符;

3、 输入的文件可能带路径,记录文件名称不能带路径。也就是说,哪怕不同路径下的文件,如果它们的名字的后16个字符相同,也被视为相同的错误记录

4、循环记录时,只以第一次出现的顺序为准,后面重复的不会更新它的出现时间,仍以第一次为准

数据范围:错误记录数量满足 1≤n≤100  ,每条记录长度满足 1 ≤len≤100 

输入描述:

每组只包含一个测试用例。一个测试用例包含一行或多行字符串。每行包括带路径文件名称,行号,以空格隔开。

输出描述:

将所有的记录统计并将结果输出,格式:文件名 代码行数 数目,一个空格隔开,如:

方法一:暴力法

#include
#include
using namespace std;

string getfilename(string filepath){ //题取文件名
    string res = "";
    for(int i = filepath.length() - 1; i >= 0; i--){ //逆向查找到第一个斜杠
        if(filepath[i] ==  '\\')
            break;
        res = filepath[i] + res; //将字符加到字符串前面
    }
    if(res.length() > 16) //长度大于16的时候,截取后16位
        res = res.substr(res.length() - 16, 16);
    return  res;
}

bool find(vector, int>>& record, string& file, int num){ //找到出现过的文件名和行号
    for(int i = 0; i < record.size(); i++){
        if(record[i].first.first == file && record[i].first.second == num){ //文件名和行号相同
            record[i].second++; //直接在后面添加出现次数
            return true;
        }
    }
    return false;
}

void findoutput(vector, int>>& record, string& file, int num){ //打印该错误出现的次数
    for(int i = 0; i < record.size(); i++){
        if(record[i].first.first == file && record[i].first.second == num){ //文件名和行号相同
            cout << record[i].second << endl; //直接输出次数
            return;
        }
    }
}

int main(){
    string filepath;
    int num; 
    vector, int> > record; //记录文件名、行号、出现次数
    vector > res(8, {"", 0}); 
    int index = 0; //记录下标
    while(cin >> filepath >> num){
        string file = getfilename(filepath); //提取文件名
        if(!find(record, file, num)){ //出现新的才添加
            record.push_back(make_pair(make_pair(file, num), 1)); //记录中添加一个全新的
            res[index] = make_pair(file, num);
            index = (index + 1) % 8; //循环
        }
    }
    for(int i = 0; i < 8; i++){
        if(res[index].first != ""){ //只输出有记录的,防止不足8个
            cout << res[index].first << " " << res[index].second << " ";
            findoutput(record, res[index].first, res[index].second);
        }
        index = (index + 1) % 8;
    }
    return 0;
}

 方法二:哈希表

华为机考108题(c++)(17-22)_第2张图片

#include
#include
#include
using namespace std;

string getfilename(string filepath){ //题取文件名
    string res = "";
    for(int i = filepath.length() - 1; i >= 0; i--){ //逆向查找到第一个斜杠
        if(filepath[i] ==  '\\')
            break;
        res = filepath[i] + res; //将字符加到字符串前面
    }
    if(res.length() > 16) //长度大于16的时候,截取后16位
        res = res.substr(res.length() - 16, 16);
    return  res;
}

int main(){
    string filepath, num; //把路径和行号都当成字符串
    unordered_map mp;
    vector res(8, "");
    int index = 0; //记录下标
    while(cin >> filepath >> num){
        string file = getfilename(filepath);
        string key = file + " " + num;
        if(mp.find(key) == mp.end()){ //没有出现过,需要添加到哈希表中
            mp[key] = 1;
            res[index] = key;
            index = (index + 1) % 8; //循环记录
        }else
            mp[key]++; //遇到相同的错误,计数增加
    }
    for(int i = 0; i < 8; i++){
        if(res[index] != "") //只输出有记录的,防止不足8个
            cout << res[index] << " " << mp[res[index]] << endl;
        index = (index + 1) % 8;
    }
    return 0;
}

 HJ20 密码验证合格程序

描述

密码要求:

1.长度超过8位

2.包括大小写字母.数字.其它符号,以上四种至少三种

3.不能有长度大于2的不含公共元素的子串重复 (注:其他符号不含空格或换行)

数据范围:输入的字符串长度满足 1≤n≤100 

输入描述:

一组字符串。

输出描述:

如果符合要求输出:OK,否则输出NG

方法一:暴力验证

华为机考108题(c++)(17-22)_第3张图片

#include
#include
using namespace std;

int main(){
    string s;
    while(cin >> s){
        if(s.length() <= 8){ //长度不超过不可行
            cout << "NG" << endl;
            continue;
        }
        int flag[4] = {0};
        for(int i  = 0; i < s.length(); i++){
            if(s[i] >= 'A' && s[i] <= 'Z') //大写字母
                flag[0] = 1;
            else if(s[i] >= 'a' && s[i] <= 'z') //小写字母
                flag[1] = 1;
            else if(s[i] >= '0' && s[i] <= '9') //数字
                flag[2] = 1;
            else  //其他符号
                flag[3] = 1;
        }
        if(flag[0] + flag[1] + flag[2] + flag[3] < 3){ //符号少于三种
            cout << "NG" << endl;
            continue;
        }
        bool repute = false; //记录重复子串
        for(int i = 0; i <= s.length() - 6; i++) //遍历检查是否有长度为3的相同的字串
            for(int j = i + 3; j < s.length(); j++)
                if(s.substr(i, 3) == s.substr(j, 3)){
                    repute = true;
                    break;
                }
        if(repute) //有重复
            cout << "NG" << endl;
        else 
            cout << "OK" << endl;
    }
    return 0;
}

 方法二:正则表达式

#include
#include
#include
using namespace std;

int main(){
    string s;
    while(cin >> s){
        if(s.length() <= 8){ //长度不超过不可行
            cout << "NG" << endl;
            continue;
        }
        string re[4] = { "[a-z]", "[A-Z]", "\\d", "[^a-zA-Z0-9]" }; //分别匹配小写字母、大写字母、数字、其他字符
		int count = 0;
		for (int i = 0; i < 4; i++) {
			regex pattern(re[i]);
			if (regex_search(s, pattern)) //只需要查找到,不要求完全匹配
				count++;
		}
        if(count < 3){ //符号少于三种
            cout << "NG" << endl;
            continue;
        }
        regex pattern(".*(...)(.*\\1).*"); //匹配串前后连续3个字符一样的
        if(regex_search(s, pattern))
            cout << "NG" << endl;
        else
            cout << "OK" << endl;
    }
    return 0;
}

 HJ21 简单密码

描述

现在有一种密码变换算法。

九键手机键盘上的数字与字母的对应: 1--1, abc--2, def--3, ghi--4, jkl--5, mno--6, pqrs--7, tuv--8 wxyz--9, 0--0,把密码中出现的小写字母都变成九键键盘对应的数字,如:a 变成 2,x 变成 9.

而密码中出现的大写字母则变成小写之后往后移一位,如:X ,先变成小写,再往后移一位,变成了 y ,例外:Z 往后移是 a 。

数字和其它的符号都不做变换。

数据范围: 输入的字符串长度满足 1 \le n \le 100 \1≤n≤100 

输入描述:

输入一组密码,长度不超过100个字符。

输出描述:

输出密码变换后的字符串

方法一:查表法

华为机考108题(c++)(17-22)_第4张图片

#include
#include
using namespace std;
const string dict1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";//解密前
const string dict2="bcdefghijklmnopqrstuvwxyza22233344455566677778889999";//解密后
 


int main(){
    string str;
    while(getline(cin,str)){//逐行输入
        for(int i=0;i

方法二:遍历发

#include

using namespace std;

int main(){
    string str;
    while(cin>>str){
        for(int i=0;i='A' && str[i]<'Z'){//大写字母变成小写字母后移一位
                str[i] = str[i] + 33;
            }
            else if(str[i] == 'Z'){
                str[i] = 'a';
            }else if(str[i]>='a' && str[i]<='c'){//abc--2
                str[i] = '2';
            }else if(str[i]>='d' && str[i]<='f'){//def--3
                str[i] = '3';
            }else if(str[i]>='g' && str[i]<='i'){//ghi--4
                str[i] = '4';
            }else if(str[i]>='j' && str[i]<='l'){//jkl--5
                str[i] = '5';
            }else if(str[i]>='m' && str[i]<='o'){//mno--6
                str[i] = '6';
            }else if(str[i]>='p' && str[i]<='s'){//pqrs--7
                str[i] = '7';
            }else if(str[i]>='t' && str[i]<='v'){//tuv--8
                str[i] = '8';
            }else if(str[i]>='w' && str[i]<='z'){//wxyz--9
                str[i] = '9';
            }
        }
        cout<

 HJ22 汽水瓶

描述

某商店规定:三个空汽水瓶可以换一瓶汽水,允许向老板借空汽水瓶(但是必须要归还)。

小张手上有n个空汽水瓶,她想知道自己最多可以喝到多少瓶汽水。

数据范围:输入的正整数满足 1 \le n \le 100 \1≤n≤100 

注意:本题存在多组输入。输入的 0 表示输入结束,并不用输出结果。

输入描述:

输入文件最多包含 10 组测试数据,每个数据占一行,仅包含一个正整数 n( 1<=n<=100 ),表示小张手上的空汽水瓶数。n=0 表示输入结束,你的程序不应当处理这一行。

输出描述:

对于每组测试数据,输出一行,表示最多可以喝的汽水瓶数。如果一瓶也喝不到,输出0。

方法一:递归

华为机考108题(c++)(17-22)_第5张图片

#include
using namespace std;

int recursion(int n){
    if(n == 1) //只剩1个空瓶,没办法喝到
        return 0;
    if(n == 2) //剩2个空瓶,可以喝一瓶
        return 1;
    return recursion(n - 2) + 1; //减去三个空瓶得到可以喝一瓶,之后得到一个空瓶
}

int main(){
    int n;
    while(cin >> n){
        if(n == 0) //0表示结束
            break;
        cout << recursion(n) << endl; //递归处理
    }
    return 0;
}

 方法二:迭代

#include
using namespace std;

int main(){
    int n;
    while(cin >> n){
        if(n == 0) //0表示结束
            break;
        int count = 0;
        while(n > 2){
            count++;
            n -= 2; //每次两个空瓶换一瓶汽水
        }
        //检查最后剩余
        if(n == 2) 
            cout << ++count << endl;
        else
            cout << count << endl;
    }
    return 0;
}

方法三:数学规律

#include
using namespace std;

int main(){
    int n;
    while(cin >> n){
        if(n == 0) //0表示结束
            break;
        cout << n / 2 << endl; //直接输出n/2
    }
    return 0;
}

你可能感兴趣的:(C++,C++)