算法竞赛文件读写

发布时间 2023-09-14 17:50:48作者: catting123

freopen

使用freopen进行文件读写,可以节约测试时重复输入的时间,用法可以参考官网std::freopen - cppreference.com。程序中使用cin/coutscanf/printf均可。

模板

#include<cstdio>

using namespace std;

int main() {
    // 提交时记得将这两行注释掉
    freopen("E:\\c\\in.txt", "r", stdin);
    freopen("E:\\c\\out.txt", "w", stdout);

    // 主要代码
    // ...

    return 0;
}

例子:CCF CSP 202006-2 稀疏向量

微信截图_20230914174029

由于题目是图片形式,测试样例的输入输出无法复制,比较麻烦,所以可以使用上面的方法进行文件读写。

// 202006-2 稀疏向量
#include<iostream>
#include<cstdio>

using namespace std;
const int N = 500010;

int u[N][2], v[N][2];
int a, b, n;
long long prod;

int main() {
    // 提交时记得将这两行注释掉
    freopen("E:\\c\\in.txt", "r", stdin);
    freopen("E:\\c\\out.txt", "w", stdout);

    scanf("%d%d%d", &n, &a, &b);
    for (int i = 1; i <= a; i++) {
        scanf("%d%d", &u[i][0], &u[i][1]);
    }

    for (int i = 1; i <= b; i++) {
        scanf("%d%d", &v[i][0], &v[i][1]);
    }

    int i = 1, j = 1;

    while (i <= a && j <= b) {
        if (u[i][0] == v[j][0]) {
            prod += u[i][1] * v[j][1];
            i++, j++;
        } else if (u[i][0] < v[j][0]) {
            i++;
        } else {
            j++;
        }
    }

    printf("%d", prod);

    return 0;
}