小投入,大输出

Small input, large output?

本文关键字:输出      更新时间:2023-10-16

我对我写的这个短代码有一个问题:

#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int main() {
    ofstream fout("hps.out");
    ifstream fin("hps.in");
    int N;
    fin >> N;
    int a1, a2, b1, b2, c1, c2 = 0;
    for (int i = 0; i < N; i++) {
        int x, y;
        fin >> x;
        fin >> y;
        if (x == 1 && y == 2) {
            a1++;
        }
        if (x == 1 && y == 3) {
            a2++;
        }
        if (x == 2 && y == 1) {
            b1++;
        }
        if (x == 2 && y == 3) {
            b2++;
        }
        if (x == 3 && y == 1) {
            c1++;
        }
        if (x == 3 && y == 2) {
            c2++;
        }
    } 
    fout << a1 << " " << a2 << " " << b1 << " " << b2 << " " << c1 << " " << 
c2 << " " << 'n';
    return 0;
}

所以这是输入:

5
1 2
2 2
1 3
1 1
3 2

这是输出:

32768 4197767 0 616536480 0 1

我想做的是计算 (1,2(、(

1,3(、(2,1(、(2,3(、(3,1( 和 (3,3( 的对数,并将这些值存储在变量 a1、a2、b1、b2、c1、c2 中。然而,由于某种原因,我得到了这些巨大的数字,我不明白为什么。有什么东西溢出了吗?

这个问题的声明实际上是USACO青铜Jjanurary #2:

http://www.usaco.org/index.php?page=viewproblem2&cpid=688

我将不胜感激任何帮助!

问题出在这条线上:

int a1, a2, b1, b2, c1, c2 = 0;

这仅将 c2 初始化为零。其余的保存垃圾值。您需要为每个变量执行= 0