Branch data Line data Source code
1 : : #include <iostream>
2 : : #include <fstream>
3 : : #include <vector>
4 : : #include <cstdint>
5 : : using namespace std;
6 : :
7 : 2 : int main() {
8 : 2 : ifstream inputFile("input.txt", ios::binary);
9 [ + + ]: 2 : if (!inputFile) {
10 : 1 : cerr << "Error: Could not open input file.\n";
11 : 1 : return 1;
12 : : }
13 : 1 : vector<int> disk;
14 : 1 : uint64_t idx = 0;
15 : 1 : int id = 0;
16 : 1 : uint64_t checksum = 0;
17 [ + + ]: 20000 : for (istreambuf_iterator<char> it(inputFile), end; it != end; ++it, ++idx) {
18 [ + + ]: 19999 : disk.insert(disk.end(), *it - '0', idx & 1 ? -1 : id++);
19 : : }
20 : :
21 [ + + ]: 45807 : for (int freeIdx = 0, usedIdx = static_cast<int>(disk.size()) - 1; freeIdx <= usedIdx; --usedIdx) {
22 [ + + ]: 45806 : if(disk[usedIdx] != -1) {
23 [ + + + - : 49828 : while (disk[freeIdx] != -1 && freeIdx <= usedIdx) {
+ + ]
24 : 25962 : checksum += freeIdx * disk[freeIdx];
25 : 25962 : ++freeIdx;
26 : : }
27 : :
28 [ + + ]: 23866 : if (freeIdx < usedIdx) {
29 : 23865 : checksum += freeIdx++ * disk[usedIdx]; // Update checksum for swapped values
30 : : }
31 : : }
32 : : }
33 : :
34 : 1 : cout << checksum << endl;
35 [ + + ]: 3 : }
|