Allen is hosting a formal dinner party. 2n 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 1≤n≤100), the number of pairs of people.
The second line contains k-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→11323244→11332244 also works in the same number of steps.
The second sample case already satisfies the constraints; therefore we need 0 swaps.
题意 如何让一对一对匹配成功
1和1 匹配 2和2 匹配。。。(总感觉在虐狗)
只能两两交换位置移动
题解
从第一个开始找是否匹配,如果不匹配就从前往后找,找到后‘那一段’往后挪一个单位
代码如下
#include<bits/stdc++.h> using namespace std; int a[205]; int main(){ int n; while(~scanf("%d",&n)){ for(int i=0;i<2*n;i++){ scanf("%d",&a[i]); } int ans=0; int pos; for(int i=1;i<2*n;i+=2){ if(a[i]!=a[i-1]){ int t=a[i]; for(int j=i+1;j<2*n;j++){ if(a[j]==a[i-1]){ ans+=j-i; pos=j; a[i]=a[j]; break; } } //这个就是那一段 for(int j=pos;j>i;j--){ a[j]=a[j-1]; } a[i+1]=t; } // for(int j=0;j<2*n;j++){ // printf("%d ",a[j]); // } // printf("\n"); } printf("%d\n",ans); } return 0; }