Codeforces Round #492 D. Suit and Tie

题意:给了n对数,每一对的数是一样的,只有相邻的数可以交换,求最少的交换次数使得相邻的两个数是一对的

分析:贪心,对于最左边的数,找到它右边的配对,交换过去,再找次左边的数和配对,交换。。直到满足题意为止

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int a[210],mp[210];
int main()
{
    int n,cnt = 0;
    cin>>n;
    for(int i = 1; i <= 2 * n; i++)
    {
        cin>>a[i];
    }
    for(int i = 1; i <= 2 * n; i += 2)
    {
        for(int j = 2 * n; j >= 1; j--)
        {
            if(a[j] == a[i])
            {
               while(j > i && a[j] != a[j - 1])
               {
                  swap(a[j],a[j - 1]);
                  j--;
                  cnt++;
               }
               break;
            }

        }
    }
    cout<<cnt<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhlbjtu2016/article/details/81108002