【离散化 线段树 二分查找】3661可以被机器人摧毁的最大墙壁数目|2525
本文涉及知识点
【C++】树状数组的使用、原理、封装类、样例
C++线段树
C++二分查找
3661. 可以被机器人摧毁的最大墙壁数目
一条无限长的直线上分布着一些机器人和墙壁。给你整数数组 robots ,distance 和 walls:
robots[i] 是第 i 个机器人的位置。
distance[i] 是第 i 个机器人的子弹可以行进的 最大 距离。
walls[j] 是第 j 堵墙的位置。
每个机器人有 一颗 子弹,可以向左或向右发射,最远距离为 distance[i] 米。
子弹会摧毁其射程内路径上的每一堵墙。机器人是固定的障碍物:如果子弹在到达墙壁前击中另一个机器人,它会 立即 在该机器人处停止,无法继续前进。
返回机器人可以摧毁墙壁的 最大 数量。
注意:
墙壁和机器人可能在同一位置;该位置的墙壁可以被该位置的机器人摧毁。机器人不会被子弹摧毁。
示例 1:
输入: robots = [4], distance = [3], walls = [1,10]
输出: 1
解释:
robots[0] = 4 向 左 发射,distance[0] = 3,覆盖范围 [1, 4],摧毁了 walls[0] = 1。
因此,答案是 1。
示例 2:
输入: robots = [10,2], distance = [5,1], walls = [5,2,7]
输出: 3
解释:
robots[0] = 10 向 左 发射,distance[0] = 5,覆盖范围 [5, 10],摧毁了 walls[0] = 5 和 walls[2] = 7。
robots[1] = 2 向 左 发射,distance[1] = 1,覆盖范围 [1, 2],摧毁了 walls[1] = 2。
因此,答案是 3。
示例 3:
输入: robots = [1,2], distance = [100,1], walls = [10]
输出: 0
解释:
在这个例子中,只有 robots[0] 能够到达墙壁,但它向 右 的射击被 robots[1] 挡住了,因此答案是 0。
提示:
1 < = r o b o t s . l e n g t h = = d i s t a n c e . l e n g t h < = 1 0 5 1 <= robots.length == distance.length <= 10^5 1<=robots.length==distance.length<=105
1 < = w a l l s . l e n g t h < = 1 0 5 1 <= walls.length <= 10^5 1<=walls.length<=105
1 < = r o b o t s [ i ] , w a l l s [ j ] < = 1 0 9 1 <= robots[i], walls[j] <= 10^9 1<=robots[i],walls[j]<=109
1 < = d i s t a n c e [ i ] < = 1 0 5 1 <= distance[i] <= 10^5 1<=distance[i]<=105
robots 中的所有值都是 互不相同 的
错误解法 线段树+ 动态规划
动态规划的状态表示
dp[i]表示 只摧毁位置 ≤ i \le i ≤i的墙,最后能销毁多少堵墙。且之后不会消耗 ≤ i \le i ≤i的墙。
最大值线段树maxTree记录最大值。
动态规划的顺序
按机器人的位置从小到大处理。
动态规划的转移方程
每个机器人枚举两种状态,向左射击,向右射击。
动态规划的初始值
全为0.
动态规划的返回值
maxTree的最大值。
错误原因
由于两个机器人的射击范围不能重叠,否则会重复统计。故向左射击不一定是最大射程,各射程要一一枚举。
robots = { 4,10 }, distance = { 3,3 }, walls = { 6,7,8 };
第二个机器人向左射击能到{7,8,9,10}。第一个机器人向右射击到7,第二各机器人向左射击到8,才是正解。
错误代码
template<classTSave,classTRecord>classCRangUpdateLineTree{protected:virtualvoidOnQuery(TSave& ans,const TSave& save,constint& iSaveLeft,constint& iSaveRight)=0;virtualvoidOnUpdate(TSave& save,constint& iSaveLeft,constint& iSaveRight,const TRecord& update)=0;virtualvoidOnUpdateParent(TSave& par,const TSave& left,const TSave& r,constint& iSaveLeft,constint& iSaveRight)=0;virtualvoidOnUpdateRecord(TRecord& old,const TRecord& newRecord)=0;};template<classTSave,classTRecord>classCVectorRangeUpdateLineTree:publicCRangUpdateLineTree<TSave,TRecord>{public:CVectorRangeUpdateLineTree(int iEleSize, TSave tDefault, TRecord tRecordNull):m_iEleSize(iEleSize),m_tDefault(tDefault),m_save(iEleSize *4, tDefault),m_record(iEleSize *4, tRecordNull){ m_recordNull = tRecordNull;}voidUpdate(int iLeftIndex,int iRightIndex, TRecord value){Update(1,0, m_iEleSize -1, iLeftIndex, iRightIndex, value);} TSave Query(int leftIndex,int rightIndex){returnQuery(leftIndex, rightIndex, m_tDefault);} TSave Query(int leftIndex,int rightIndex,const TSave& tDefault){ TSave ans = tDefault;Query(ans,1,0, m_iEleSize -1, leftIndex, rightIndex);return ans;}//void Init() {// Init(1, 0, m_iEleSize - 1);//} TSave QueryAll(){return m_save[1];}voidswap(CVectorRangeUpdateLineTree<TSave, TRecord>& other){ m_save.swap(other.m_save); m_record.swap(other.m_record); std::swap(m_recordNull, other.m_recordNull);assert(m_iEleSize == other.m_iEleSize);}protected://void Init(int iNodeNO, int iSaveLeft, int iSaveRight)//{// if (iSaveLeft == iSaveRight) {// this->OnInit(m_save[iNodeNO], iSaveLeft);// return;// }// const int mid = iSaveLeft + (iSaveRight - iSaveLeft) / 2;// Init(iNodeNO * 2, iSaveLeft, mid);// Init(iNodeNO * 2 + 1, mid + 1, iSaveRight);// this->OnUpdateParent(m_save[iNodeNO], m_save[iNodeNO * 2], m_save[iNodeNO * 2 + 1], iSaveLeft, iSaveRight);//}voidQuery(TSave& ans,int iNodeNO,int iSaveLeft,int iSaveRight,int iQueryLeft,int iQueryRight){if((iSaveLeft >= iQueryLeft)&&(iSaveRight <= iQueryRight)){this->OnQuery(ans,m_save[iNodeNO], iSaveLeft, iSaveRight);return;}if(iSaveLeft == iSaveRight){//没有子节点return;}Fresh(iNodeNO, iSaveLeft, iSaveRight);constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2;if(mid >= iQueryLeft){Query(ans,iNodeNO *2, iSaveLeft, mid, iQueryLeft, iQueryRight);}if(mid +1<= iQueryRight){Query(ans,iNodeNO *2+1, mid +1, iSaveRight, iQueryLeft, iQueryRight);}}voidUpdate(int iNode,int iSaveLeft,int iSaveRight,int iOpeLeft,int iOpeRight, TRecord value){if((iOpeLeft <= iSaveLeft)&&(iOpeRight >= iSaveRight)){this->OnUpdate(m_save[iNode], iSaveLeft, iSaveRight, value);this->OnUpdateRecord(m_record[iNode], value);return;}if(iSaveLeft == iSaveRight){return;//没有子节点}Fresh(iNode, iSaveLeft, iSaveRight);constint iMid = iSaveLeft +(iSaveRight - iSaveLeft)/2;if(iMid >= iOpeLeft){Update(iNode *2, iSaveLeft, iMid, iOpeLeft, iOpeRight, value);}if(iMid +1<= iOpeRight){Update(iNode *2+1, iMid +1, iSaveRight, iOpeLeft, iOpeRight, value);}// 如果有后代,至少两个后代this->OnUpdateParent(m_save[iNode], m_save[iNode *2], m_save[iNode *2+1], iSaveLeft, iSaveRight);}voidFresh(int iNode,int iDataLeft,int iDataRight){if(m_recordNull == m_record[iNode]){return;}constint iMid = iDataLeft +(iDataRight - iDataLeft)/2;Update(iNode *2, iDataLeft, iMid, iDataLeft, iMid, m_record[iNode]);Update(iNode *2+1, iMid +1, iDataRight, iMid +1, iDataRight, m_record[iNode]); m_record[iNode]= m_recordNull;} vector<TSave> m_save; vector<TRecord> m_record; TRecord m_recordNull; TSave m_tDefault;constint m_iEleSize;};template<classTSave,classTRecord>classCTreeRangeLineTree:publicCRangUpdateLineTree<TSave,TRecord>{protected:structCTreeNode{intCnt()const{return m_iMaxIndex - m_iMinIndex +1;}int m_iMinIndex;int m_iMaxIndex; TRecord record; TSave data; CTreeNode* m_lChild =nullptr,* m_rChild =nullptr;}; CTreeNode* m_root; TSave m_tDefault; TRecord m_tRecordDef;public:CTreeRangeLineTree(int iMinIndex,int iMaxIndex, TSave tDefault, TRecord tRecordDef){ m_tDefault = tDefault; m_tRecordDef = tRecordDef; m_root =CreateNode(iMinIndex, iMaxIndex);}voidUpdate(int iLeftIndex,int iRightIndex, TRecord value){Update(m_root, iLeftIndex, iRightIndex, value);} TSave QueryAll(){return m_root->data;} TSave Query(int leftIndex,int leftRight){ TSave ans = m_tDefault;Query(ans,m_root, leftIndex, leftRight);return ans;}protected:voidQuery(TSave& ans, CTreeNode* node,int iQueryLeft,int iQueryRight){if((node->m_iMinIndex >= iQueryLeft)&&(node->m_iMaxIndex <= iQueryRight)){this->OnQuery(ans, node->data, node->m_iMinIndex, node->m_iMaxIndex);return;}if(1== node->Cnt()){//没有子节点return;}CreateChilds(node);Fresh(node);constint mid = node->m_iMinIndex +(node->m_iMaxIndex - node->m_iMinIndex)/2;if(mid >= iQueryLeft){Query(ans, node->m_lChild, iQueryLeft, iQueryRight);}if(mid +1<= iQueryRight){Query(ans, node->m_rChild, iQueryLeft, iQueryRight);}}voidUpdate(CTreeNode* node,int iOpeLeft,int iOpeRight, TRecord value){constint& iSaveLeft = node->m_iMinIndex;constint& iSaveRight = node->m_iMaxIndex;if((iOpeLeft <= iSaveLeft)&&(iOpeRight >= iSaveRight)){this->OnUpdate(node->data, iSaveLeft, iSaveRight, value);this->OnUpdateRecord(node->record, value);return;}if(1== node->Cnt()){//没有子节点return;}CreateChilds(node);Fresh(node);constint mid = node->m_iMinIndex +(node->m_iMaxIndex - node->m_iMinIndex)/2;if(mid >= iOpeLeft){this->Update(node->m_lChild, iOpeLeft, iOpeRight, value);}if(mid +1<= iOpeRight){this->Update(node->m_rChild, iOpeLeft, iOpeRight, value);}// 如果有后代,至少两个后代this->OnUpdateParent(node->data, node->m_lChild->data, node->m_rChild->data, node->m_iMinIndex, node->m_iMaxIndex);}voidCreateChilds(CTreeNode* node){if(nullptr!= node->m_lChild){return;}constint iSaveLeft = node->m_iMinIndex;constint iSaveRight = node->m_iMaxIndex;constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2; node->m_lChild =CreateNode(iSaveLeft, mid); node->m_rChild =CreateNode(mid +1, iSaveRight);} CTreeNode*CreateNode(int iMinIndex,int iMaxIndex){ CTreeNode* node =new CTreeNode; node->m_iMinIndex = iMinIndex; node->m_iMaxIndex = iMaxIndex; node->data = m_tDefault; node->record = m_tRecordDef;return node;}voidFresh(CTreeNode* node){if(m_tRecordDef == node->record){return;}CreateChilds(node);Update(node->m_lChild, node->m_lChild->m_iMinIndex, node->m_lChild->m_iMaxIndex, node->record);Update(node->m_rChild, node->m_rChild->m_iMinIndex, node->m_rChild->m_iMaxIndex, node->record); node->record = m_tRecordDef;}};template<classTSave,classTRecord>classCSetMaxLineTree:publicCTreeRangeLineTree<TSave,TRecord>{public:using CTreeRangeLineTree<TSave, TRecord>::CTreeRangeLineTree;protected:virtualvoidOnQuery(TSave& ans,const TSave& save,constint& iSaveLeft,constint& iSaveRight){ ans =max(ans, save);}virtualvoidOnUpdate(TSave& save,constint& iSaveLeft,constint& iSaveRight,const TRecord& update){ save = update;}virtualvoidOnUpdateParent(TSave& par,const TSave& left,const TSave& r,constint& iSaveLeft,constint& iSaveRight){ par =max(left, r);}virtualvoidOnUpdateRecord(TRecord& old,const TRecord& newRecord){ old = newRecord;}};classSolution{public:intmaxWalls(vector<int>& robots, vector<int>& distance, vector<int>& walls){constint N = robots.size();constint M =(int)(1e9+2e5);sort(walls.begin(), walls.end()); vector<pair<int,int>> rd;for(int i =0; i < N; i++){ rd.emplace_back(robots[i], distance[i]);}sort(rd.begin(), rd.end()); vector<int>vLeft(N),vRight(N);for(int i =0; i < N;i++){constauto&[pos, dis]= rd[i];constint iLeftRobot = i ? rd[i -1].first :1; vLeft[i]=max(iLeftRobot, pos - dis);constint iRightPos =(i+1==N)? M : rd[i+1].first; vRight[i]=min(iRightPos, pos + dis);} CSetMaxLineTree<int,int>maxTree(0, M,0,0);for(int i =0; i < N; i++){constint x1 =max(1,vLeft[i]), x2 = rd[i].first, x3 =min(M,vRight[i]);constint cnt1 =upper_bound(walls.begin(), walls.end(), x2)-lower_bound(walls.begin(), walls.end(), x1);constint left = maxTree.Query(0, x1 -1)+ cnt1;constint cnt2 =upper_bound(walls.begin(), walls.end(), x3)-lower_bound(walls.begin(), walls.end(), x2);constint right = maxTree.Query(0, x2 -1)+ cnt2; maxTree.Update(x2,x2, left); maxTree.Update(x3, x3, right);}return maxTree.QueryAll();}};正确解法
某个向右的机器人和某个向左的机器人射程重叠后。向右的机器人射程不变,向左的机器人缩短射程使之不重叠。向右射击仍然是一种状态,故只讨论向左。
令向左的机器人位于x2,向左能射击到x1。
则:射程非最大向左的最大值为 max x 1 x 2 − 1 ( d p [ x ] + f ( x ) ) \max_{x1}^{x2-1}( dp[x] + f(x)) maxx1x2−1(dp[x]+f(x)),其中f(x)是处于 x + 1 ∼ x 2 的墙数 x+1 \sim x2的墙数 x+1∼x2的墙数,令g(x)是 ≤ x \le x ≤x的墙数。
则 射程非最大向左的最大值为 max x 1 x 2 − 1 ( d p [ x ] + g ( x 2 ) − g ( x ) ) = g ( x 2 ) + max x 1 x 2 − 1 ( d p [ x ] − g ( x ) ) \max_{x1}^{x2-1}( dp[x] +g(x2)-g(x))=g(x2)+\max_{x1}^{x2-1}( dp[x] -g(x)) maxx1x2−1(dp[x]+g(x2)−g(x))=g(x2)+maxx1x2−1(dp[x]−g(x))
我们用最大值线段树maxTree2记录:dp[x]−g(x)
向左射击的最大值为:max(射程非最大向左的最大值,射程最大向左的最大值)
向右也要枚举
比如:
robots ={3,5}, distance ={2,2}, walls ={4,6};令向右的机器人在x2,向右能射击到x3。为了避免和前面的机器人重叠,我将此机器人的射程调整为: x + 1 → x 3 x+1 \rightarrow x3 x+1→x3
则起点非x2向右的最大值为: max x : x 2 x 3 − 1 d p [ x ] + ( x + 1 ∼ x 3 ) 的墙的个数 = g ( x 3 ) + max x : x 2 x 3 − 1 ( d p [ x ] − g ( x ) ) \max_{x:x2}^{x3-1}dp[x]+(x+1 \sim x3)的墙的个数=g(x3)+\max_{x:x2}^{x3-1}(dp[x]-g(x)) maxx:x2x3−1dp[x]+(x+1∼x3)的墙的个数=g(x3)+maxx:x2x3−1(dp[x]−g(x))
可以共用:maxTree2。
内存超限代码
template<classTSave,classTRecord>classCSingeUpdateLineTree{protected:virtualvoidOnQuery(TSave& ans,const TSave& cur)=0;virtualvoidOnUpdate(TSave& save,int iSave,const TRecord& update)=0;virtualvoidOnUpdateParent(TSave& par,const TSave& left,const TSave& r,int iSaveLeft,int iSaveRight)=0;};template<classTSave,classTRecord>classCVectorSingUpdateLineTree:publicCSingeUpdateLineTree<TSave,TRecord>{public:CVectorSingUpdateLineTree(int iEleSize, TSave tDefault):m_iEleSize(iEleSize),m_save(iEleSize*4,tDefault),m_tDefault(tDefault){}voidUpdate(int index, TRecord update){Update(1,0, m_iEleSize-1, index, update);} TSave Query(int leftIndex,int leftRight,TSave tDefault){ TSave ans = tDefault;Query(ans,1,0, m_iEleSize -1, leftIndex, leftRight);return ans;} TSave Query(int leftIndex,int leftRight){returnQuery(leftIndex,leftRight, m_tDefault);}voidInit(std::function<void(TSave&,constint&)> fun){Init(fun,1,0, m_iEleSize -1);} TSave QueryAll(){return m_save[1];}protected:int m_iEleSize;voidInit(std::function<void(TSave&,constint&)> fun,int iNodeNO,int iSaveLeft,int iSaveRight){if(iSaveLeft == iSaveRight){fun(m_save[iNodeNO], iSaveLeft);return;}constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2;Init(fun,iNodeNO *2, iSaveLeft, mid);Init(fun,iNodeNO *2+1, mid +1, iSaveRight);this->OnUpdateParent(m_save[iNodeNO], m_save[iNodeNO*2], m_save[iNodeNO*2+1], iSaveLeft, iSaveRight);}voidQuery(TSave& ans,int iNodeNO,int iSaveLeft,int iSaveRight,int iQueryLeft,int iQueryRight){if((iSaveLeft >= iQueryLeft)&&(iSaveRight <= iQueryRight)){this->OnQuery(ans,m_save[iNodeNO]);return;}if(iSaveLeft == iSaveRight){//没有子节点return;}constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2;if(mid >= iQueryLeft){Query(ans,iNodeNO *2, iSaveLeft, mid, iQueryLeft, iQueryRight);}if(mid +1<= iQueryRight){Query(ans,iNodeNO *2+1, mid +1, iSaveRight, iQueryLeft, iQueryRight);}}voidUpdate(int iNodeNO,int iSaveLeft,int iSaveRight,int iUpdateNO, TRecord update){if(iSaveLeft == iSaveRight){this->OnUpdate(m_save[iNodeNO], iSaveLeft, update);return;}constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2;if(iUpdateNO <= mid){Update(iNodeNO *2, iSaveLeft, mid, iUpdateNO, update);}else{Update(iNodeNO *2+1, mid +1, iSaveRight, iUpdateNO, update);}this->OnUpdateParent(m_save[iNodeNO], m_save[iNodeNO*2], m_save[iNodeNO*2+1], iSaveLeft, iSaveRight);} vector<TSave> m_save;const TSave m_tDefault;};template<classTSave,classTRecord>classCTreeSingeLineTree:publicCSingeUpdateLineTree<TSave,TRecord>{protected:structCTreeNode{intCnt()const{return m_iMaxIndex - m_iMinIndex +1;}int m_iMinIndex;int m_iMaxIndex; TSave data; CTreeNode* m_lChild=nullptr,*m_rChild=nullptr;~CTreeNode(){delete m_lChild; m_lChild =nullptr;delete m_rChild; m_rChild =nullptr;}}; CTreeNode* m_root; TSave m_tDefault;public:CTreeSingeLineTree(int iMinIndex,int iMaxIndex, TSave tDefault){ m_tDefault = tDefault; m_root =CreateNode(iMinIndex, iMaxIndex);}voidUpdate(int index, TRecord update){Update(m_root, index, update);} TSave QueryAll(){return m_root->data;} TSave Query(int leftIndex,int leftRight){ TSave ans = m_tDefault;Query(ans,m_root, leftIndex, leftRight);return ans;}~CTreeSingeLineTree(){delete m_root;}protected:voidQuery(TSave& ans,CTreeNode* node,int iQueryLeft,int iQueryRight){if((node->m_iMinIndex >= iQueryLeft)&&(node->m_iMaxIndex <= iQueryRight)){this->OnQuery(ans,node->data);return;}if(1== node->Cnt()){//没有子节点return;}CreateChilds(node);constint mid = node->m_iMinIndex +(node->m_iMaxIndex - node->m_iMinIndex)/2;if(mid >= iQueryLeft){Query(ans,node->m_lChild, iQueryLeft, iQueryRight);}if(mid +1<= iQueryRight){Query(ans,node->m_rChild, iQueryLeft, iQueryRight);}}voidUpdate(CTreeNode* node,int iUpdateNO, TRecord update){if((iUpdateNO < node->m_iMinIndex)||(iUpdateNO > node->m_iMaxIndex)){return;}if(1== node->Cnt()){this->OnUpdate(node->data, node->m_iMinIndex, update);return;}CreateChilds(node);Update(node->m_lChild, iUpdateNO, update);Update(node->m_rChild, iUpdateNO, update);this->OnUpdateParent(node->data, node->m_lChild->data, node->m_rChild->data, node->m_iMinIndex, node->m_iMaxIndex);}voidCreateChilds(CTreeNode* node){if(nullptr!= node->m_lChild){return;}constint iSaveLeft = node->m_iMinIndex;constint iSaveRight = node->m_iMaxIndex;constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2; node->m_lChild =CreateNode(iSaveLeft,mid); node->m_rChild =CreateNode(mid+1, iSaveRight);} CTreeNode*CreateNode(int iMinIndex,int iMaxIndex){ CTreeNode* node =new CTreeNode; node->m_iMinIndex = iMinIndex; node->m_iMaxIndex = iMaxIndex; node->data = m_tDefault;return node;}};template<classTSave,classTRecord>classCSetMaxLineTree:publicCTreeSingeLineTree<TSave,TRecord>{public:using CTreeSingeLineTree<TSave, TRecord>::CTreeSingeLineTree;protected:virtualvoidOnQuery(TSave& ans,const TSave& cur){ ans =max(ans, cur);}virtualvoidOnUpdate(TSave& save,int iSave,const TRecord& updatee){ save = updatee;}virtualvoidOnUpdateParent(TSave& par,const TSave& left,const TSave& r,int iSaveLeft,int iSaveRight){ par =max(left, r);}};classSolution{public:intmaxWalls(vector<int>& robots, vector<int>& distance, vector<int>& walls){constint N = robots.size();constint M =(int)(1e9+2e5);sort(walls.begin(), walls.end()); vector<pair<int,int>> rd;for(int i =0; i < N; i++){ rd.emplace_back(robots[i], distance[i]);}sort(rd.begin(), rd.end()); vector<int>vLeft(N),vRight(N);for(int i =0; i < N;i++){constauto&[pos, dis]= rd[i];constint iLeftRobot = i ? rd[i -1].first :1; vLeft[i]=max(iLeftRobot, pos - dis);constint iRightPos =(i+1==N)? M : rd[i+1].first; vRight[i]=min(iRightPos, pos + dis);} CSetMaxLineTree<int,int>maxTree(0, M,0),maxTree2(0, M,-1000'000);for(int i =0; i < N; i++){constint x1 =max(1,vLeft[i]), x2 = rd[i].first, x3 =min(M,vRight[i]);constint g2 =upper_bound(walls.begin(), walls.end(), x2)- walls.begin();constint g3 =upper_bound(walls.begin(), walls.end(), x3)- walls.begin();constint cnt1 =upper_bound(walls.begin(), walls.end(), x2)-lower_bound(walls.begin(), walls.end(), x1);constint left = maxTree.Query(0, x1 -1)+ cnt1;constint cnt2 =upper_bound(walls.begin(), walls.end(), x3)-lower_bound(walls.begin(), walls.end(), x2);constint right = maxTree.Query(0, x2 -1)+ cnt2;constint left2 = maxTree2.Query(x1,x2-1)+g2;constint right2 = maxTree2.Query(x2, x3 -1)+ g3; maxTree.Update(x2,max(left,left2)); maxTree.Update(x3,max(right,right2)); maxTree2.Update(x2,max(left, left2)-g2); maxTree2.Update(x3,max(right, right2)-g3);}return maxTree.QueryAll();}};空间超限的解决方法
一,离散化。
二,改用最大值树状数组。
核心代码
template<classT=int>classCDiscretize//离散化{public:CDiscretize(vector<T> nums){sort(nums.begin(), nums.end()); nums.erase(std::unique(nums.begin(), nums.end()), nums.end()); m_nums = nums;for(int i =0; i < nums.size(); i++){ m_mValueToIndex[nums[i]]= i;}}intoperator[](const T value)const{auto it = m_mValueToIndex.find(value);if(m_mValueToIndex.end()== it){return-1;}return it->second;}intsize()const{return m_mValueToIndex.size();} vector<T> m_nums;protected: unordered_map<T,int> m_mValueToIndex;};template<classTSave,classTRecord>classCSingeUpdateLineTree{protected:virtualvoidOnQuery(TSave& ans,const TSave& cur)=0;virtualvoidOnUpdate(TSave& save,int iSave,const TRecord& update)=0;virtualvoidOnUpdateParent(TSave& par,const TSave& left,const TSave& r,int iSaveLeft,int iSaveRight)=0;};template<classTSave,classTRecord>classCVectorSingUpdateLineTree:publicCSingeUpdateLineTree<TSave,TRecord>{public:CVectorSingUpdateLineTree(int iEleSize, TSave tDefault):m_iEleSize(iEleSize),m_save(iEleSize*4,tDefault),m_tDefault(tDefault){}voidUpdate(int index, TRecord update){Update(1,0, m_iEleSize-1, index, update);} TSave Query(int leftIndex,int leftRight,TSave tDefault){ TSave ans = tDefault;Query(ans,1,0, m_iEleSize -1, leftIndex, leftRight);return ans;} TSave Query(int leftIndex,int leftRight){returnQuery(leftIndex,leftRight, m_tDefault);}voidInit(std::function<void(TSave&,constint&)> fun){Init(fun,1,0, m_iEleSize -1);} TSave QueryAll(){return m_save[1];}protected:int m_iEleSize;voidInit(std::function<void(TSave&,constint&)> fun,int iNodeNO,int iSaveLeft,int iSaveRight){if(iSaveLeft == iSaveRight){fun(m_save[iNodeNO], iSaveLeft);return;}constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2;Init(fun,iNodeNO *2, iSaveLeft, mid);Init(fun,iNodeNO *2+1, mid +1, iSaveRight);this->OnUpdateParent(m_save[iNodeNO], m_save[iNodeNO*2], m_save[iNodeNO*2+1], iSaveLeft, iSaveRight);}voidQuery(TSave& ans,int iNodeNO,int iSaveLeft,int iSaveRight,int iQueryLeft,int iQueryRight){if((iSaveLeft >= iQueryLeft)&&(iSaveRight <= iQueryRight)){this->OnQuery(ans,m_save[iNodeNO]);return;}if(iSaveLeft == iSaveRight){//没有子节点return;}constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2;if(mid >= iQueryLeft){Query(ans,iNodeNO *2, iSaveLeft, mid, iQueryLeft, iQueryRight);}if(mid +1<= iQueryRight){Query(ans,iNodeNO *2+1, mid +1, iSaveRight, iQueryLeft, iQueryRight);}}voidUpdate(int iNodeNO,int iSaveLeft,int iSaveRight,int iUpdateNO, TRecord update){if(iSaveLeft == iSaveRight){this->OnUpdate(m_save[iNodeNO], iSaveLeft, update);return;}constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2;if(iUpdateNO <= mid){Update(iNodeNO *2, iSaveLeft, mid, iUpdateNO, update);}else{Update(iNodeNO *2+1, mid +1, iSaveRight, iUpdateNO, update);}this->OnUpdateParent(m_save[iNodeNO], m_save[iNodeNO*2], m_save[iNodeNO*2+1], iSaveLeft, iSaveRight);} vector<TSave> m_save;const TSave m_tDefault;};template<classTSave,classTRecord>classCTreeSingeLineTree:publicCSingeUpdateLineTree<TSave,TRecord>{protected:structCTreeNode{intCnt()const{return m_iMaxIndex - m_iMinIndex +1;}int m_iMinIndex;int m_iMaxIndex; TSave data; CTreeNode* m_lChild=nullptr,*m_rChild=nullptr;~CTreeNode(){delete m_lChild; m_lChild =nullptr;delete m_rChild; m_rChild =nullptr;}}; CTreeNode* m_root; TSave m_tDefault;public:CTreeSingeLineTree(int iMinIndex,int iMaxIndex, TSave tDefault){ m_tDefault = tDefault; m_root =CreateNode(iMinIndex, iMaxIndex);}voidUpdate(int index, TRecord update){Update(m_root, index, update);} TSave QueryAll(){return m_root->data;} TSave Query(int leftIndex,int leftRight){ TSave ans = m_tDefault;Query(ans,m_root, leftIndex, leftRight);return ans;}~CTreeSingeLineTree(){delete m_root;}protected:voidQuery(TSave& ans,CTreeNode* node,int iQueryLeft,int iQueryRight){if((node->m_iMinIndex >= iQueryLeft)&&(node->m_iMaxIndex <= iQueryRight)){this->OnQuery(ans,node->data);return;}if(1== node->Cnt()){//没有子节点return;}CreateChilds(node);constint mid = node->m_iMinIndex +(node->m_iMaxIndex - node->m_iMinIndex)/2;if(mid >= iQueryLeft){Query(ans,node->m_lChild, iQueryLeft, iQueryRight);}if(mid +1<= iQueryRight){Query(ans,node->m_rChild, iQueryLeft, iQueryRight);}}voidUpdate(CTreeNode* node,int iUpdateNO, TRecord update){if((iUpdateNO < node->m_iMinIndex)||(iUpdateNO > node->m_iMaxIndex)){return;}if(1== node->Cnt()){this->OnUpdate(node->data, node->m_iMinIndex, update);return;}CreateChilds(node);Update(node->m_lChild, iUpdateNO, update);Update(node->m_rChild, iUpdateNO, update);this->OnUpdateParent(node->data, node->m_lChild->data, node->m_rChild->data, node->m_iMinIndex, node->m_iMaxIndex);}voidCreateChilds(CTreeNode* node){if(nullptr!= node->m_lChild){return;}constint iSaveLeft = node->m_iMinIndex;constint iSaveRight = node->m_iMaxIndex;constint mid = iSaveLeft +(iSaveRight - iSaveLeft)/2; node->m_lChild =CreateNode(iSaveLeft,mid); node->m_rChild =CreateNode(mid+1, iSaveRight);} CTreeNode*CreateNode(int iMinIndex,int iMaxIndex){ CTreeNode* node =new CTreeNode; node->m_iMinIndex = iMinIndex; node->m_iMaxIndex = iMaxIndex; node->data = m_tDefault;return node;}};template<classTSave,classTRecord>classCSetMaxLineTree:publicCVectorSingUpdateLineTree<TSave,TRecord>{public:using CVectorSingUpdateLineTree<TSave, TRecord>::CVectorSingUpdateLineTree;protected:virtualvoidOnQuery(TSave& ans,const TSave& cur){ ans =max(ans, cur);}virtualvoidOnUpdate(TSave& save,int iSave,const TRecord& updatee){ save =max(save,updatee);}virtualvoidOnUpdateParent(TSave& par,const TSave& left,const TSave& r,int iSaveLeft,int iSaveRight){ par =max(left, r);}};classSolution{public:intmaxWalls(vector<int>& robots, vector<int>& distance, vector<int>& walls){ N = robots.size();Init(robots,distance,walls); CSetMaxLineTree<int,int>maxTree(M+1,0),maxTree2(M+1,-1000'000);for(constauto&[x1,x2,x3]: m_xs){constint g2 =upper_bound(walls.begin(), walls.end(), x2)- walls.begin();constint g3 =upper_bound(walls.begin(), walls.end(), x3)- walls.begin();constint cnt1 =upper_bound(walls.begin(), walls.end(), x2)-lower_bound(walls.begin(), walls.end(), x1);constint left = maxTree.Query(0, x1 -1)+ cnt1;constint cnt2 =upper_bound(walls.begin(), walls.end(), x3)-lower_bound(walls.begin(), walls.end(), x2);constint right = maxTree.Query(0, x2 -1)+ cnt2;constint left2 = maxTree2.Query(x1,x2-1)+g2;constint right2 = maxTree2.Query(x2, x3 -1)+ g3; maxTree.Update(x2,max(left,left2)); maxTree.Update(x3,max(right,right2)); maxTree2.Update(x2,max(left, left2)-g2); maxTree2.Update(x3,max(right, right2)-g3);}return maxTree.QueryAll();}voidInit(const vector<int>& robots,const vector<int>& distance, vector<int>& walls){ vector<pair<int,int>> rd;sort(walls.begin(), walls.end());auto tmp = walls; tmp.emplace_back(INT_MIN /2);//编码增加0,实际编码从1开始for(int i =0; i < N; i++){ rd.emplace_back(robots[i], distance[i]); tmp.emplace_back(robots[i]);} CDiscretize<int>disc(tmp);for(auto& i : walls){ i = disc[i];}sort(rd.begin(), rd.end());for(int i =0; i < N; i++){constauto&[pos, dis]= rd[i];constint iLeftRobot = i ? rd[i -1].first :1;constint iLeft =max(iLeftRobot, pos - dis);constint iRightRobot =(i +1== N)?(INT_MAX/2): rd[i +1].first;constint iRight =min(iRightRobot, pos + dis);constint x1 =lower_bound(disc.m_nums.begin(), disc.m_nums.end(), iLeft)- disc.m_nums.begin();constint x2 = disc[pos];constint x3 =upper_bound(disc.m_nums.begin(), disc.m_nums.end(), iRight)- disc.m_nums.begin()-1; m_xs.emplace_back(x1, x2, x3);} M = disc.m_nums.size();}int N, M; vector<tuple<int,int,int>> m_xs;};单元测试
vector<int> robots, distance, walls;TEST_METHOD(TestMethod00){ robots ={4,10}, distance ={3,3}, walls ={6,7,8};auto res =Solution().maxWalls(robots, distance, walls);AssertEx(3, res);}TEST_METHOD(TestMethod01){ robots ={3,5}, distance ={2,2}, walls ={4,6};auto res =Solution().maxWalls(robots, distance, walls);AssertEx(2, res);}TEST_METHOD(TestMethod11){ robots ={4}, distance ={3}, walls ={1,10};auto res =Solution().maxWalls(robots, distance, walls);AssertEx(1, res);}TEST_METHOD(TestMethod12){ robots ={10,2}, distance ={5,1}, walls ={5,2,7};auto res =Solution().maxWalls(robots, distance, walls);AssertEx(3, res);}TEST_METHOD(TestMethod13){ robots ={1,2}, distance ={100,1}, walls ={10};auto res =Solution().maxWalls(robots, distance, walls);AssertEx(0, res);}TEST_METHOD(TestMethod14){ robots ={17,59,32,11,72,18}, distance ={5,7,6,5,2,10}, walls ={17,25,33,29,54,53,18,35,39,37,20,14,34,13,16,58,22,51,56,27,10,15,12,23,45,43,21,2,42,7,32,40,8,9,1,5,55,30,38,4,3,31,36,41,57,28,11,49,26,19,50,52,6,47,46,44,24,48};auto res =Solution().maxWalls(robots, distance, walls);AssertEx(37, res);}TEST_METHOD(TestMethod15){ robots ={31,22,4,43,8,38,5,15,35,37,27,42,40,28,20,21}, distance ={3,5,5,7,8,1,10,7,9,6,3,4,4,5,7,4}, walls ={34,74,54,46,79,89,7,73,12,27,44,5,62,43,60,71,10,63,41,77,33,91,32,53,66,51,78,18,61,6,8,24,23,81,3,25,40,85,84,15,52,48,17,59,55,64,50,21,88,36,2,16,80,69,22,87,1,28,65,31,83,26,67,72,29,75,57,9,30,86,39,37,13,19,56,68,35,90};auto res =Solution().maxWalls(robots, distance, walls);AssertEx(41, res);}简单版
性质一:如果机器人和墙挨着一起,此墙一定被摧毁。故只考虑不挨着机器人的墙。
性质二:由于子弹遇到机器人会停止,故墙只会被相邻的机器人摧毁。比赛的时候,没有挖掘到此性质。
动态规划的状态表示
dp0n表示第 0 ∼ i 0 \sim i 0∼i号机器人都已经射击完毕,且最后一个机器人向左(右)射击能摧毁最后的墙数。
空间复杂度:O(n)
为了方便处理边界情况,增加一个机器人标兵,射击距离都是0,位置分别在正负无穷大。
动态规划的填表顺序
n = 1 to N 枚举后继状态和选择。
动态规划的转移方程
如果 i-1 和 i 都向左射击,两者不会摧毁同一道墙。
如果 i-1 向右和 i 向左射击,两者可能摧毁同一道墙。需要出度重复。i向右能够摧毁g1道墙,i-1向左能够摧毁g0道墙,i和i-1之间的机器人数量c,则重复的墙数为: m a x ( 0 , g 1 + g 0 − c ) max(0,g1+g0-c) max(0,g1+g0−c)。
如果i向右射击,i-1无论向左还是向右,两者都不会摧毁同一道墙。
动态规划的初始值
全为0。
动态规划的返回值
max ( d p 0. b a c k ( ) , d p 1. b a c k ( ) ) \max(dp0.back(),dp1.back()) max(dp0.back(),dp1.back())
代码
classSolution{public:intmaxWalls(vector<int>& robots, vector<int>& distance, vector<int>& walls){constint N = robots.size();constint M =int(1e9+1e5+1);sort(walls.begin(), walls.end()); vector<pair<int,int>> rd;for(int i =0; i < N; i++){ rd.emplace_back(robots[i], distance[i]);} rd.emplace_back(INT_MIN /2,0); rd.emplace_back(INT_MAX /2,0);sort(rd.begin(), rd.end()); vector<int>vLeft(N+2),vRight(N+2);for(int i =0; i < rd.size(); i++){constauto&[pos, dis]= rd[i];constint iLeftRobot = i ? rd[i -1].first :-M; vLeft[i]=max(iLeftRobot, pos - dis-1);constint iRightRobot =(i +1== N+2)? M : rd[i +1].first; vRight[i]=min(iRightRobot, pos + dis+1);}auto Cnt =[&](int left,int r){int ans =lower_bound(walls.begin(), walls.end(), r)-upper_bound(walls.begin(), walls.end(), left);return ans;};//(left,r)之间的墙数量,不包括left,r。 vector<int>dp0(N +2),dp1(N +2);for(int n =1; n <= N; n++){ dp1[n]=max(dp0[n -1], dp1[n -1])+Cnt(rd[n].first,vRight[n]);constint g =Cnt(vLeft[n], rd[n].first); dp0[n]= dp0[n-1]+ g;constint iRepeat = g +Cnt(rd[n-1].first,vRight[n-1])-Cnt(rd[n -1].first, rd[n].first); dp0[n]=max(dp0[n], dp1[n -1]+ g -max(0,iRepeat));}int cntSamePos =0;for(constauto& pos : robots){ cntSamePos +=Cnt(pos-1, pos+1);}return cntSamePos+max(dp0[N], dp1[N]);}};扩展阅读
| 我想对大家说的话 |
|---|
| 工作中遇到的问题,可以按类别查阅鄙人的算法文章,请点击《算法与数据汇总》。 |
| 学习算法:按章节学习《喜缺全书算法册》,大量的题目和测试用例,打包下载。重视操作 |
| 有效学习:明确的目标 及时的反馈 拉伸区(难度合适) 专注 |
| 员工说:技术至上,老板不信;投资人的代表说:技术至上,老板会信。 |
| 闻缺陷则喜(喜缺)是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。 |
| 子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。 |
| 如果程序是一条龙,那算法就是他的是睛 |
| 失败+反思=成功 成功+反思=成功 |
视频课程
先学简单的课程,请移步ZEEKLOG学院,听白银讲师(也就是鄙人)的讲解。
https://edu.ZEEKLOG.net/course/detail/38771
如何你想快速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
https://edu.ZEEKLOG.net/lecturer/6176
测试环境
操作系统:win7 开发环境: VS2019 C++17
或者 操作系统:win10 开发环境: VS2022 C++17
如无特殊说明,本算法用**C++**实现。