算法与数据结构(十四):IO 模板总结(C++ & Python)

不少网络笔试不像 LeetCode 帮你完成 I/O,需要手动完成;个人深受其痛,现将常用的 IO 模板总结与此,分别总结了 C/C++ 和 Python 代码

1. 输入不说明有多少个 Input,以 EOF 为结束标志

C++

    int a, b;
    while (cin >> a >> b) {
        // ...
    }

2. 输入不说明有多少个 Input,以某个特殊输入为结束标志

C++

    // 示例 1
    int a, b;
    while (cin >> a >> b) {
        if (a == 0 && b == 0)
            break;
        // ...
    }
    
    // 示例 2
    int n;
    while (cin >> n && n != 0) {
        // ...
    }

3. 指示有 N 个 Input

C++

    int n;
    cin >> n;
    
    int a, b;
    while(n--) {
        cin >> a >> b;
    }

Python3

n = int(input())
for _ in range(n):
    # ...

4. 指示有 N 组输入,并以某个特殊输入退出

C/C++

    int n;
    while (cin >> n && n != 0) {
        int a, b;
        for (int i = 0; i < n; i++) {
            cin >> a >> b;
            // ...
        }
    }

5. 输入是一整行(包括空格)

用 char[] 接收(C/C++)

    const int MAXN = 1000;
    char buff[MAXN];
    
    // C
    gets(buff);
    puts(buff); // 输出
    
    // C++
    cin.getline(buff, MAXN);  // 第三个参数默认是 '\n'
    cin.getline(buff, MAXN, '\n');

用 string 接收(C++)

    string s;
    getline(cin, s);          // 第三个参数默认是 '\n'
    getline(cin, s, '\n');

6. 输入是多行(包括空格)

C++

    int n;
    cin >> n;
    cin.get();  // 否则,n 也会计入下面的 getline(),导致少一组数据
    
    while (n--) {
        string s;
        getline(cin, s);
    }

7. 从文件读取

C++

    ifstream fin("in.txt");
    ofstream fout("out.txt");
    
    int a, b;
    while (fin >> a >> b) {
        fout << a + b << endl;
    }
    
    fin.close();
    fout.close();

8. Python IO 模板

在笔试时,有时候用 Python 进行数据处理比 C++ 要方便很多,但是如何能够顺利地读入数据呢?如果使用input(),那么输入时不能有空格分割,这不是我们想要的。 比如我们需要一次读取一行,可以使用sys.stdin.

    for line in sys.stdin
        #operate(line)
        #print(line)

这样可以一次读取一整行。 也可以这样做:

    while True:
        line = sys.stdin.readline()
        #operate(line)
        #print(line)
        if line == ''
            break

还有,如果在输出时,print 的换行很不好用的话,可以使用sys.stdout.write(),这样容易控制整个输出。

    def test():
        N = int(input())
        inputlist = []
        area = 0
        for i in range(N):
            line = input()
            line_res = rule(line)
            print(line_res)

9. 牛客网 IO 模板

def insert_sort2():
    N = int(input())
    str_input = input()
    ary = list(map(int, str_input.split()))
    # count = len(ary)
    for i in range(1, N):
        key = i - 1
        mark = ary[i]  # 注: 必须将ary[i]赋值为mark,不能直接用ary[i]
        while key >= 0 and ary[key] > mark:
            if (ary[key] + mark)%2 == 1:
                ary[key + 1] = ary[key]
            key -= 1
        ary[key + 1] = mark
    res = sorted(ary)
    return res
9.1 单行输入

在这里插入图片描述

在这里插入图片描述
C++

// 本题为考试单行多行输入输出规范示例,无需提交,不计分。
#include <iostream>
using namespace std;
int main() {
    int a,b;
    while(cin >> a >> b)// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例
        cout << a+b << endl;
}

Python

#coding=utf-8
# 本题为考试单行多行输入输出规范示例,无需提交,不计分。
import sys 
for line in sys.stdin:
    a = line.split()
	print(int(a[0]) + int(a[1]))
n = int(input())
for i in range(n):
	values = list(map(int, input().strip().split()))
	print(values[0] + values[1])
9.2 多行输入

在这里插入图片描述

在这里插入图片描述
C++

// 本题为考试多行输入输出规范示例,无需提交,不计分。
#include <iostream>
#include <cstdio>
 
using namespace std;
 
int main(){
    //freopen("1.in","r",stdin);
    int n,ans = 0;
    cin >> n;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            int x; scanf("%d",&x);
            ans += x;
        }
    }
    cout << ans << endl;
    return 0;
}

Python

#coding=utf-8
# 本题为考试多行输入输出规范示例,无需提交,不计分。
import sys
if __name__ == "__main__":
    # 读取第一行的n
    n = int(input())
    ans = 0
    for i in range(n):
        # 读取每一行
        line = input()
        # 或者 line = sys.stdin.readline()
     
        # 把每一行的数字分隔后转化成int列表
        values = list(map(int, line.strip().split()))
        for v in values:
            ans += v
    print(ans)

注:有一些时候 牛客网要求输出多行,每行结果对应一个 testcase 输入处理,这种情况下可以直接在 main 函数中进行 for 循环调用函数,输出结果。

参考文献

[1] Python IO 模板
[2] 备忘-IO 模板
[3] 牛客网标准输入输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值