Luogu: P1966 matches line up (increased + / provincial election -, divide and conquer)

topic:

Insert picture description here

Analysis: At first, there was no idea. Take a look at the problem solution to merge and sort. So think about it for yourself.

If one is ordered, then the other is also ordered, so that the minimum value will be obtained.

Then the problem is transformed into a series of numbers, which is ordered after the minimum number of exchanges.

After thinking about it for a long time, I didn’t expect it, so I looked at the solution carefully.

It was found that the neighbors were missing before they could move. (I realized that this question should have been done on the leetcode, and I didn’t see the adjacent ones to move)

It's clear, will it be superfluous if the movement on the left and right becomes orderly?

Perceptual knowledge will not.

Emphasize: only need to consider moving forward or only need to consider moving backward, that's it! ! ! ! ! (Marked as the essence of the reason)

Worth thinking about it!

Therefore, only considering the forward movement, then there must be only the forward movement in the back half. And when neither pointer points to the last element, that is, there are elements to be placed in both parts.

Code:? ? The state is not good, let it go for the time being.

Insert picture description here

#include<bits/stdc++.h>
using namespace std;
#include<bits/stdc++.h>
using namespace std;
int m;
int B[100005];
int ans=0;
struct node{
    
    
 int x1;
 int x2;
} A[100005];
bool cmp(node n1,node n2)
{
    
    
 return n1.x2<n2.x2;
}
void f(int x,int y)
{
    
    //包括下标为x和下标为y的。   从小到大排序 
 if(x==y) return;
 if(x+1==y)
 {
    
    
  if(A[x].x1>A[y].x1) {
    
    
   ans++; swap(A[x].x1,A[y].x1);
   ans=ans%(100000000-3);
  }
  return;
 } 
 int c=(x+y)/2;
 f(x,c);
 f(c+1,y);
 //合并
 int b1=x,b2=c+1;//合并时的两个指针 
 int bb=x;
 while(1)
 {
    
    
  if(b1==c+1 && b2==y+1) break;
  if(b1==c+1)
  {
    
    
   B[bb]=A[b2].x1;bb++;b2++;
  }
  else if(b2==y+1)
  {
    
    
   B[bb]=A[b1].x1;bb++;b1++;
  }
  else{
    
    
   if(A[b1].x1>A[b2].x1) 
   {
    
    
    B[bb]=A[b2].x1;bb++;b2++;
    ans=ans+b2-bb;
    ans=ans%(100000000-3);
    }
   else{
    
    
    B[bb]=A[b1].x1;bb++;b1++;
   }
  }
 }
  for(int i=x;i<=y;i++)
  {
    
    
    A[i].x1=B[i];
 }
}
int main()
{
    
    
  cin>>m; 
  for(int i=0;i<m;i++) cin>>A[i].x1;
  for(int i=0;i<m;i++) cin>>A[i].x2;
  sort(A,A+m,cmp);
  /*for(int i=0;i<m;i++)
  {
   cout<<A[i].x1<<' '<<A[i].x2<<endl;
   } */
  f(0,m-1);
  cout<<ans;
}

Guess you like

Origin blog.csdn.net/weixin_42721412/article/details/108553343