Codeforce-995B(暴力+思维)

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≤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

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
4
1 1 2 3 3 2 4 4
Output
2
Input
3
1 1 2 2 3 3
Output
0
Input
3
3 1 2 3 1 2
Output
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.

  • 题目大意:对于给定的一列数,通过和相邻的数字交换位置,目的是使相同的数字相邻。求最小的交换次数。
  • 思路:定义两个数组,a数组用来储存数据,b数组用来利用下标记录该下标的数字是否完成配对。然后对其进行枚举处理。详细见代码注释
  • AC Code
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    
    int a[1005];
    int b[105];  //记录是否完成配对 
    int main()
    {
        int n;
        scanf("%d",&n);
        for(int i=1; i<=2*n; i++)
        {
            scanf("%d",&a[i]);
            b[a[i]] = 0;
        }
        int ans=0;
        for(int i=1; i<=2*n; i++)
        {
            if(b[a[i]])	continue;        //完成配对的,则跳过 
            int cnt = 0;                 //记录一对数字之间未完成配对的数字的个数 
            for(int j=i+1;j<=2*n;j++)
            {
                if(b[a[j]])	cnt++;
                if(a[j]==a[i])	ans = ans + j-i-1-cnt;  //需要移动的次数 
            }
            b[a[i]] = 1;
        }
        printf("%d\n",ans);
    
        return 0;
    } 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值