soldiers

# Meaning of problems
n soldiers, the position of each soldier is represented by a pair of integers (x, y), the soldiers may be moved up and down each time can be moved, by moving all the soldiers in the same horizontal line on, i.e., the same x y adjacent to find the minimum number of moves, each soldier can occupy only a single position.

# Solution to a problem
if seeking simple median of abscissa, a condition which can not meet the adjacent,
the sort of x, such that the required minimum number of soldiers all adjacent moving. Then before and after the move, the relative position of the soldier . is constant
for example, referred to add soldier prior position after the movement leftmost
X [. 1] -> add +. 1;
X [2] -> add + 2;
...
X [n-] -> add + n;
converting at
X [. 1] -. 1 -> the Add;
X [2] - 2 -> the Add;
...
X [n-] - n--> the Add;
after treatment, is transformed in order to move to the same point in the case of , can be done directly with the median

 1 #include<bits/stdc++.h>
 2 #define ll long long
 3 #define ld long double
 4 #define pii pair<int,int>
 5 using namespace std;
 6 const int N=1e4+10;
 7 int x[N],y[N];
 8 int n;
 9 int main(){
10    ios::sync_with_stdio(0);
11    cin.tie(0);
12    cout.tie();
13    cin>>n;
14    int ans=0;
15    for(int i=1;i<=n;i++)
16       cin>>x[i]>>y[i];
17    sort(x+1,x+1+n);
18    sort(y+1,y+1+n);
19    for(int i = 1; i <= n; i++)
20       x[i]-=i;
21    sort(x+1,x+1+n);
22 
23 
24    for(int i = 1; i <= n; i++)
25       ans += abs(x[i] - x[(n+1)>>1]);
26 
27    for(int i = 1; i <= n; i++)
28       ans += abs(y[i] - y[(n+1)>>1]);
29    cout<<ans;
30 }

 

Guess you like

Origin www.cnblogs.com/hhyx/p/12432268.html