A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: 317.
The text file, keylog.txt, contains fifty successful login attempts.
Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible secret passcode of unknown length.
先整理出每个出现在每个数字前面和后面的数字
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <fstream>
using namespace std;
int main()
{
ifstream input;
input.open("keylog.txt");
vector<string>s;
string line;
while (!input.eof())
{
input >> line;
s.push_back(line);
}
set<char> a[10][2];
for (int i = 0; i < s.size(); i++)
{
a[s[i][0] - '0'][1].insert(s[i][1]);
a[s[i][0] - '0'][1].insert(s[i][2]);
a[s[i][1] - '0'][1].insert(s[i][2]);
a[s[i][1] - '0'][0].insert(s[i][0]);
a[s[i][2] - '0'][0].insert(s[i][0]);
a[s[i][2] - '0'][0].insert(s[i][1]);
}
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j < 2; j++)
{
if (j == 0)
{
cout << "出现在" << i << "前面的数:";
}
else
cout << "出现在" << i << "后面的数:";
for (set<char>::iterator p = a[i][j].cbegin(); p != a[i][j].cend(); ++p)
cout << *p << " ";
cout << endl;
}
}
system("pause");
return 0;
}
得到的结果如下:
很明显密码中不出现4和5,并且7前面没有别的数字,意味着7是第一个数字,然后出现在三前面的数字只有7,确定了第二个数字为3
再根据1前面出现的数字为3,7,确定第三个个数字为1,依次根据6,2,8,9,0前面出现的数字,最后得到密码为73162890