CodeForces - 996D 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个数字,使得任意相等的数字都相邻,最少的操作次数,操作为:交换相邻两个数字的位置。

思路:从后往前对每一个数,把他后面对应的数字交换到他的旁边,这样下去就是最优解。这样每一个数前面都是已经匹配好的,而且把后面的数字往前走总是在减少他们的距离,而其他的数字之间的距离不可能增大,有些甚至会减少。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
typedef long long ll;
const int maxn = 4e5 + 5;
ll a[maxn];
int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        for(int i = 1; i <= 2*n; i++)
            scanf("%lld", &a[i]);
        ll ans = 0;
        for(int i = 1; i <= 2*n; i+=2)
        {
            if(a[i] == a[i+1]) continue;
            else
            {
                for(int j = i + 1; j <= 2*n; j++)
                {
                    if(a[j] == a[i])
                    {
                        ans += j-i-1;
                        for(int k = j; k > i+1; k--)
                            swap(a[k], a[k-1]);
                        break;
                    }

                }
            }
        }
        printf("%lld\n", ans);
    }
    return 0;
}




猜你喜欢

转载自blog.csdn.net/qq_34374664/article/details/80895710