二分法,按位二分,时间复杂度o(N),空间复杂度临时变量。
文件流,以输出流形式打开文件时,源文件内容会被清空;输入输出流形式,源文件内容只是覆盖。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int get_lost(string file1,string file2,string file3,int length,int bit)
{
int lost=0;
int f2_count,f3_count;
int a;
ifstream f1(file1.c_str());
if(!f1)
{
cerr<<"can not open file: "<<file1<<endl;
return -1;
}
ofstream f2(file2.c_str());
if(!f2)
{
std::cerr<<"can not open file: "<<file2<<endl;
return -1;
}
ofstream f3(file3.c_str());
if(!f3)
{
std::cerr<<"can not open file: "<<file3<<endl;
return -1;
}
if(length==(unsigned long)(1<<bit))
return -1;
while(bit--){
f2_count=0,f3_count=0;
//cout<<"round "<<bit<<endl;
for(int i=0;i<length;i++)
{
f1>>a;
// cout<<a<<endl;
if(a&(1<<bit))
{
f2<<a<<endl;
f2_count++;
}
else{
f3<<a<<endl;
f3_count++;
}
}
// int tmp;
// cout<<"f2_count"<<f2_count<<endl;
/*f2.seekg(0,ios::beg);
while(f2>>tmp)
{
cout<<tmp<<endl;
cout<<"-------------------------------"<<endl;
}
f3.seekg(0,ios::beg);
cout<<"f3_count"<<f3_count<<endl;
while(f3>>tmp)
{
cout<<tmp<<endl;
cout<<"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl;
}*/
f1.close();
f2.close();
f3.close();
f1.clear();
f2.clear();
f3.clear();
if(f2_count<=f3_count)
{
length=f2_count;
f1.open(file2.c_str());
f2.open(file1.c_str());
f3.open(file3.c_str());
lost+=(1<<bit);
//cout<<"lost "<<lost;
}
else{
length=f3_count;
f1.open(file3.c_str());
f2.open(file2.c_str());
f3.open(file1.c_str());
lost+=(0<<bit);
// cout<<"lost "<<lost;
}
}
return lost;
}
int main(void)
{
string ifile;
string tmp="tmp.txt",tmp2="tmp2.txt";
cin>>ifile;
cout<<get_lost(ifile,tmp,tmp2,14,4)<<endl;
//一下内容测试文件流,何时覆盖、何时清空文件
fstream test("tmp3.txt");
for(int i=0;i<10;i++)
{
test<<i<<endl;
}
test.close();
test.clear();
test.open("tmp3.txt");
test<<"1"<<endl;//不清空
ofstream test2("tmp3.txt");
test2<<"2"<<endl;//清空
}