Allen is hosting a formal dinner party. 2n2n people come to the event in nn pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.
Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.
The first line contains a single integer nn (1≤n≤1001≤n≤100), the number of pairs of people.
The second line contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n. For each ii with 1≤i≤n1≤i≤n, ii appears exactly twice. If aj=ak=iaj=ak=i, that means that the jj-th and kk-th people in the line form a couple.
Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.
4 1 1 2 3 3 2 4 4
2
3 1 1 2 2 3 3
0
3 3 1 2 3 1 2
3
In the first sample case, we can transform 11233244→11232344→1122334411233244→11232344→11223344 in two steps. Note that the sequence 11233244→11323244→1133224411233244→11323244→11332244 also works in the same number of steps.
The second sample case already satisfies the constraints; therefore we need 00
swaps
题意:给出一个n,有2×n的数列,每个数字必定出现两次,你可以进行互换操作,即将相邻的两个数互换。问,将所有相同的数字移动到一起,最少需要互换几次。
思路:前面的数字是不动的!如 3 1 2 3 1 2,我们肯定是选择将后面的一那个3往前移动!(如果将前面的3移动到后面的话,在移动1和2时,都将多跨过一个数字,这就使得移动次数不是最少了)照这个思路,for循环,一个一个的开始移动就好了,毕竟n只有100,2*n也才200.
#include <iostream> using namespace std; int a[210]; int main() { int n,j,ans=0; cin>>n; for(int i=1;i<=2*n;++i) cin>>a[i]; for(int i=2;i<=2*n;i+=2){ for(j=i;j<=2*n;j++) if(a[j]==a[i-1]) break;//如果两个数相等,记下这个数的下标 for(;j>i;j--) swap(a[j],a[j-1]),ans++;//将这个数不断与他前面的数互换,直到这个数处于另一个数的后面一位 } cout<<ans<<endl; return 0; }