现有一块长方形土地,可看成n个小方块组成,这n个小方块依次编号为1-n,现要在这块土地上种A、B两种庄稼,需将该快土地划分成两大块,如果划分结果在第i块和第i+1块之间,则输出{i,i+1},i可以取0或n,这种情况说明有一种庄稼没有种。
专家经过m次鉴定,确定哪个小块适合种那种庄稼,每次鉴定,如果适合种Ai+1庄稼标记为1,适合种B庄稼标记为0,现设计一程序,确定土地划分,使得你划分的土地的小方块和专家鉴定的结果的小方块不一致的个数最少,如果有多解,则取i最大的那个(即右边划分的最少的情况)
例如:
//有4个小方块,专家鉴定了3次
输入{{1,1,1,1},{0,0,0,0},{1,0,1,1}},4,3
输出{0,1}
代码实现:
Land.h
#pragma once #include <iostream> #include <vector> #include <math.h> using namespace std; class Partition { public: vector<int> getPartition(const vector<vector<int> >& land, int n, int m) { int count = pow(2, n) - 1;//可能划分的情况共有count种 int i = 0, j = 0; int dstres = n*m; int lessCount = 0; while (count >= 0){ int flag = 0; int k = 1; int tmp = count; while (count > 1){ int ret = (tmp >> 0) & 0x01; while (k < n){ if (ret != ((tmp >> k) & 0x01)){ flag++; if (flag == 2){ count--; break; } ret = (tmp >> k) & 0x01; } k++; } if (flag != 2) break; k=1; } int res = 0; while (i<m){ int sum = 0; while (j<n){ sum = sum << 1; sum += land[i][j]; j++; } sum = sum ^ count; //统计sum转换成二进制后1的个数 while (sum){ res += sum % 2; sum /= 2; } i++; j = 0; } if (res<dstres){ dstres = res;//最少的次数 lessCount = count; } i = 0; count--; } count = lessCount; int ret = 0; int bit = count & 0x01; while (count>0 && ((count & 0x01) == bit)) { count = count >> 1; ret++; } vector<int> a = { n-ret,n-ret+1 }; return a; } };
Test.cpp
#include"Land.h" using namespace std; void Test() { Partition a; int n = 4; int m = 3; //int n = 3; //int m = 4; vector<vector<int> > land = { { 1, 1, 1, 1 }, { 0, 0, 0, 0, }, {1, 0, 1, 1} }; //vector<vector<int> > land = { { 1, 1, 0 }, { 0, 0, 0 }, { 1, 0, 1 }, {1, 0, 0} }; vector<int> array = a.getPartition(land, n, m); printf("{%d,%d}\n", array[0], array[1]); } int main() { Test(); system("pause"); return 0; }
运行结果:
输入为
{ { 1, 1, 1, 1 }, { 0, 0, 0, 0, }, {1, 0, 1, 1} } n=4 m=3
输出为
====================================================================
输入为
{ { 1, 1, 0 }, { 0, 0, 0 }, { 1, 0, 1 }, {1, 0, 0} } n=3 m=4
输出为
时间: 2024-10-06 23:47:43