给N个小球编号,其中部分连续的小球可以和另外一段连续的小球共享编号。要求使用最少的号码给每个小球编上号码。
#include <iostream>
#include <bitset>
using namespace std;
#define NUMBER_NUM 11
#define NUMBER_MAX_SHARE 5
#define MIN(a, b) ((a) <= (b) ? (a) : (b))
#define MAX(a, b) ((a) >= (b) ? (a) : (b))
typedef struct {
int begin;
int count;
} Number;
typedef struct {
Number number1;
Number number2;
} NumberSharing;
typedef struct {
int num;
int number[NUMBER_MAX_SHARE]; // 可能的前序桶的编号
bitset<NUMBER_NUM> bitmap; // 可以在同一个位置的数字
} NumberRegister;
typedef struct {
int mapping[NUMBER_NUM];
} MappingNumberult;
typedef struct {
bitset<NUMBER_NUM> bitmap;
} Pool;
const NumberSharing g_numberShare[] = {
{{2, 1}, {6, 5}},
{{4, 1}, {6, 5}},
};
bool mapping_number_register(const NumberSharing number[], int count, NumberRegister *numReg)
{
for (int i = 0; i < count; i++) {
const Number *numMin;
const Number *numMax;
if (number[i].number1.begin <= number[i].number2.begin) {
numMin = &number[i].number1;
numMax = &number[i].number2;
} else {
numMin = &number[i].number2;
numMax = &number[i].number1;
}
bitset<NUMBER_NUM> bitmapMin;
for (int j = 0; j < numMin->count; j++) {
bitmapMin.set(numMin->begin + j);
}
for (int j = 0; j < numMax->count; j++) {
NumberRegister *reg = &numReg[numMax->begin + j];
for (int k = numMin->begin; k < numMin->begin + numMin->count; k++) {
reg->number[reg->num] = k;
reg->num++;
}
}
for (int j = 0; j < numMax->count; j++) {
NumberRegister *reg = &numReg[numMax->begin + j];
reg->bitmap = reg->bitmap | bitmapMin;
}
}
return true;
}
bool mapping_number_mapping(const NumberRegister *numReg, MappingNumberult *numberult)
{
Pool pool[NUMBER_NUM] = { 0 };
int poolIndex = 0;
for (int i = 0; i < NUMBER_NUM; i++) {
const NumberRegister *reg = &numReg[i];
int loop = 0x7fff;
for (int j = 0; j < reg->num; j++) {
int k = reg->number[j];
if ((pool[k].bitmap | reg->bitmap) == reg->bitmap) {
loop = numberult->mapping[k];
break;
}
}
if (loop == 0x7fff) {
loop = poolIndex;
poolIndex++;
}
numberult->mapping[i] = loop;
pool[loop].bitmap.set(i);
}
return true;
}
bool mapping_number_map(const NumberSharing number[], int count, MappingNumberult *numberult)
{
NumberRegister numReg[NUMBER_NUM] = {0};
bool ret = mapping_number_register(number, count, numReg);
if (!ret) {
return false;
}
cout << "register result: " << ret << endl;
for (int i = 0; i < NUMBER_NUM; i++) {
cout << numReg[i].bitmap << " " << numReg[i].num << " " << numReg[i].number[0] << endl;
}
ret = mapping_number_mapping(numReg, numberult);
return ret;
}
int main(int argv, char *argc[])
{
MappingNumberult numberult = { 0 } ;
bool ret = mapping_number_map(g_numberShare, sizeof(g_numberShare) / sizeof(NumberSharing), &numberult);
cout << "tesing result: " << ret << endl;
for (int i = 0; i < NUMBER_NUM; i++) {
cout << i << " " << numberult.mapping[i] << endl;
}
return 0;
}