C++ File output and cout differ

Viewed 64

I've tried to solve finding the minimum time to print a string if all the letters of the alphabet (A-Z) form a circle:

  • The printer starts at A.
  • You can go left to right or right to left.
  • The next letter is printed from where you left off.

enter image description here

Example for string "BCY":

Going counter-clockwise here to find the minimum time. The total minimum time will be 6 seconds:

  • A to B takes 1 second
  • B to C takes 1 second
  • C to Y takes 4 seconds

Code

The inputs are an integer C that tells you which subtask to solve, and 2 strings S and T. T is only relevant for the second subtask. The output for the first task is just the minimum time required to print the string.

#include <fstream>
#include <cstring>
#include <cmath>
using namespace std;

ifstream fin("circular.in");
ofstream fout("circular.out");

bool dh (char a) {
    return a - 'A' > 12;
}
int64_t calc_min(char a, char b) {
  int64_t add = 0;
  if(dh(a) == dh(b)) {
    add = abs(a - b);
  }
  else if(dh(a) != dh(b) && dh(a) == false)
    add = min((a - 'A') + ('Z' - b) + 1, b - a);
  else if(dh(a) != dh(b) && dh(a) == true)
    add = min((b - 'A') + ('Z' - a) + 1, a - b);
  return add;
}


int main() {
  int c;
  string s, t;
  fin >> c >> s >> t;

  int64_t times = (dh(s[0]) ? 'Z' - s[0] + 1 : s[0] - 'A');
  for(unsigned i = 1; i < s.length(); i++)
    times += calc_min(s[i], s[i - 1]);

  fout << times << "\n";
  return 0;
}

Problem

The correct output is 324479. The string in test case 6 has 50000 characters but pasting 50000 characters into the console yields "26588". Pasting it into "circular.in" gives the correct answer.

If I use cin.tie && sync_with_stdio both set to false, the console bugs out with strings that are >= 800 characters, see test case 4.

Circular Problem stackoverflow on Pastebin (if you'd like to solve both subtasks). The only difference between File Input/Output and Console Input/Output is in test case 6, see https://pastebin.com/v2HeGL74

Is it normal because the string is too big or is there another reason?

0 Answers
Related