The method of taking the poj3320 ruler is basically the same as that of the question, but the range of the question is 2 ^ 31.
Sort the position of each bead.
Maintain a pointer for each type of beads to indicate which beads of this type are used.
Therefore, the ruler acquisition method is optimized by the heap. Each time the smallest value is taken from the heap, the head pointer of the ruler acquisition method is moved backward.
Then a position (pointer ++) is taken from the back of each bead (which has been sorted and increases monotonically) and added to the heap.
Add all the positions before the position of the newly added beads to the heap from each other.
Update the answer.
Until all kinds of beads are used up.
Because there may be a lot of beads at each position, a binary group is used to insert the heap.
1 #include<cstdio> 2 #include<vector> 3 #include<algorithm> 4 #include<queue> 5 using namespace std; 6 struct Point 7 { 8 int x,y; 9 Point(const int &a,const int &b)10 {11 x=a;12 y=b;13 }14 Point(){}15 };16 bool operator < (const Point &a,const Point &b){return a.x!=b.x ? a.x<b.x : a.y<b.y;}17 bool operator > (const Point &a,const Point &b){return a.x!=b.x ? a.x>b.x : a.y>b.y;}18 priority_queue<Point,vector<Point>,greater<Point> >Heap;19 vector<int>a[61];20 vector<int>::iterator p[61];21 int n,m,k,t,maxv,time[61],ans=2147483647;22 Point topv;23 int main()24 {25 scanf("%d%d",&n,&m);26 for(int i=1;i<=m;i++)27 {28 scanf("%d",&k);29 for(int j=1;j<=k;j++)30 {31 scanf("%d",&t);32 a[i].push_back(t);33 }34 sort(a[i].begin(),a[i].end());35 p[i]=a[i].begin();36 }37 for(int i=1;i<=m;i++)38 {39 maxv=max(maxv,*a[i].begin());40 Heap.push( Point( *a[i].begin() , i ) );41 p[i]++;42 time[i]++;43 }44 for(int i=1;i<=m;i++)45 for(;p[i]!=a[i].end()&&((*p[i])<=maxv);p[i]++)46 {47 time[i]++;48 Heap.push( Point( *p[i] , i ) );49 }50 while(1)51 {52 topv=Heap.top();53 int headv=topv.y;54 ans=min(ans,maxv-topv.x);55 Heap.pop();56 time[headv]--;57 if(!time[headv])58 {59 if(p[headv]==a[headv].end())60 break;61 Heap.push( Point( *p[headv] , headv ) );62 maxv=*p[headv];63 time[headv]++;64 for(int i=1;i<=m;i++)65 for(;p[i]!=a[i].end()&&((*p[i])<=maxv);p[i]++)66 {67 time[i]++;68 Heap.push( Point( *p[i] , i ) );69 }70 }71 }72 printf("%d\n",ans);73 return 0;74 }
[Heap] bzoj1293 [scoi2009] birthday gift