USACO 2.4 Fractions To Decimals

#include <algorithm>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <cmath>
#include <string>
#include <unordered_map>
#include <sstream>

using namespace std;

int N, D;
int outCnt = 1;
void format(ofstream &output) {
++outCnt;
if (outCnt == 76) {
output << endl;
outCnt = 0;
}
}

int main() {
ifstream fin("fracdec.in");
ofstream fout("fracdec.out");
fin >> N >> D;

ostringstream os;
int d = N / D;
fout << N / D;
while (d / 10) {
++outCnt;
d %= 10;
}
int r = N % D;

if (!r) {
fout << ".0" << endl;
outCnt += 2;
return 0;
} else {
fout << ".";
++outCnt;
}

vector<int> ds;
unordered_map<int, int> map;

while (r && map.find(r) == map.end()) {
map[r] = (int)ds.size();
r *= 10;
ds.push_back(r / D);
r %= D;
}

if (r) {
for (int i = 0; i < map[r]; ++i) {
fout << ds[i]; format(fout);
}

fout << "("; format(fout);

for (int i = map[r]; i < ds.size(); ++i) {
fout << ds[i]; format(fout);
}

fout << ")"; format(fout);
} else {
for (int i = 0; i < ds.size(); ++i) {
fout << ds[i]; format(fout);
}
}

fout << endl;
return 0;
}