D. Suit and Tie(水题 模拟)

D. Suit and Tie
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

The first line contains a single integer nn (1n1001≤n≤100), the number of pairs of people.

The second line contains 2n2n integers a1,a2,,a2na1,a2,…,a2n. For each ii with 1in1≤i≤nii 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

Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.

Examples
input
Copy
4
1 1 2 3 3 2 4 4
output
Copy
2
input
Copy
3
1 1 2 2 3 3
output
Copy
0
input
Copy
3
3 1 2 3 1 2
output
Copy
3
Note

In the first sample case, we can transform 11233244112323441122334411233244→11232344→11223344 in two steps. Note that the sequence 11233244113232441133224411233244→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 
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<

你可能感兴趣的:(水题)