I solve this problem in a manner that seems not straight forward. I let the fragments to "vote" on each bit if it is '0' or '1'. Specifically, for each fragment, it is either the head or tail of the file. We let it to vote as both. Thus, for each bit, there are exactly as many votes as the number of fragments, which is twice the number of files. Within these votes, we know that there are at least the number of files votes that are correct, since for each fragment, it has voted once as the correct part. Therefore, the number of correct votes is greater than or equal to the number of wrong votes. With the vote results in hand, we can reproduce the content of the original file easily.
Code:
- /*************************************************************************
- * Copyright (C) 2008 by liukaipeng *
- * liukaipeng at gmail dot com *
- *************************************************************************/
- /* @JUDGE_ID 00000 10132 C++ "File Fragmentation" */
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- using namespace std;
- int const filecount = 150;
- int const filesize = 300;
- void recover_file(char fragments[][filesize], int nfragments, char file[])
- {
- int votes[filesize][2] = {{0}};
- int lens[filecount*2] = {0};
- int len = 0;
- for (int i = 0; i < nfragments; ++i) {
- for (int j = 0; fragments[i][j] != '/0'; ++j) {
- ++votes[j][fragments[i][j] - '0'];
- ++lens[i];
- ++len;
- }
- }
- len = len * 2 / nfragments;
- for (int i = 0; i < nfragments; ++i) {
- for (int j = 0; fragments[i][j] != '/0'; ++j) {
- ++votes[len-lens[i]+j][fragments[i][j] - '0'];
- }
- }
- for (int i = 0; i < len; ++i) {
- file[i] = votes[i][0] > votes[i][1] ? '0' : '1';
- }
- }
- int main(int argc, char *argv[])
- {
- #ifndef ONLINE_JUDGE
- filebuf in, out;
- cin.rdbuf(in.open((string(argv[0]) + ".in").c_str(), ios_base::in));
- cout.rdbuf(out.open((string(argv[0]) + ".out").c_str(), ios_base::out));
- #endif
- int ncases;
- cin >> ncases;
- cin.ignore(2048, '/n').ignore(2048, '/n');
- while (ncases-- > 0) {
- char fragments[filecount*2][filesize] = {{0}};
- int nfragments = 0;
- while (cin.getline(fragments[nfragments], filesize) &&
- fragments[nfragments][0] != '/0') {
- ++nfragments;
- }
- char file[filesize] = {0};
- recover_file(fragments, nfragments, file);
- cout << file << '/n';
- if (ncases > 0) cout << '/n';
- }
- return 0;
- }