64,282
社区成员
发帖
与我相关
我的任务
分享
#include <ctime>
#include <string>
#include <vector>
#include <list>
#include <iostream>
using namespace std;
const int ele_count = 10000;
const int chr_count = 13;
struct group
{
int id;
int diff_op;
list<int> index;
};
vector<string> strs;
list<group> grps;
string random_str()
{
static char c_range[] = { '0', '1', '2' };
string rand_str;
rand_str.resize(chr_count);
for (int i = 0; i < chr_count; ++i) {
rand_str[i] = c_range[rand() % 3];
}
return(rand_str);
}
void get_elements()
{
srand(time(NULL));
strs.resize(ele_count);
for (int i = 0; i < ele_count; ++i) {
strs[i] = random_str();
}
}
void get_groups()
{
typedef list<group>::iterator liter;
for (int i = 0; i < ele_count; ++i) {
const string & rstr = strs[i];
bool need_add_grp = true;
for (liter iter = grps.begin(); grps.end() != iter; ++iter) {
group & rgrps = (*iter);
const string & rfstr = strs[rgrps.index.front()];
if (rgrps.diff_op < 0) {
int diff_cnt = 0;
int diff_op = -1;
for (int j = 0; j < chr_count; ++j) {
if (rstr[j] != rfstr[j]) {
if (1 == ++diff_cnt) {
diff_op = j;
}
else {
break;
}
}
}
if (diff_cnt > 1) {
continue;
}
if (1 == diff_cnt) {
rgrps.diff_op = diff_op;
}
rgrps.index.push_back(i);
need_add_grp = false;
break;
}
else {
bool belong = true;
for (int j = 0; j < chr_count; ++j) {
if (j != rgrps.diff_op && rstr[j] != rfstr[j]) {
belong = false;
break;
}
}
if (belong) {
rgrps.index.push_back(i);
need_add_grp = false;
break;
}
}
}
if (need_add_grp) {
group ngrp;
ngrp.id = grps.size();
ngrp.diff_op = -1;
ngrp.index.push_back(i);
grps.push_back(ngrp);
}
}
}
void check()
{
int count = 0;
typedef list<group>::iterator liter;
for (liter iter = grps.begin(); grps.end() != iter; ++iter) {
const group & rgrp = (*iter);
count += rgrp.index.size();
// cout << rgrp.id << " " << rgrp.index.size() << endl;
}
cout << count << endl;
}
int main()
{
int start = time(NULL);
get_elements();
get_groups();
int finish = time(NULL);
cout << "use time: " << (finish - start) << "s" << endl;
check();
return(0);
}