codeforces 996D Suit and Tie

http://www.elijahqi.win/archives/3869
Allen is hosting a formal dinner party. 2n

2n
people come to the event in n

n
pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n

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.

Input
The first line contains a single integer n

n
(1≤n≤100

1≤n≤100
), the number of pairs of people.

The second line contains 2n

2n
integers a1,a2,…,a2n

a1,a2,…,a2n
. For each i

i
with 1≤i≤n

1≤i≤n
, i

i
appears exactly twice. If aj=ak=i

aj=ak=i
, that means that the j

j
-th and k

k
-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 11233244→11232344→11223344

11233244→11232344→11223344
in two steps. Note that the sequence 11233244→11323244→11332244

11233244→11323244→11332244
also works in the same number of steps.

The second sample case already satisfies the constraints; therefore we need 0

0
swaps.

感觉很好的贪心 可惜菜鸡elijahqi想不到

我们考虑把所有数都往i最前面扔即可 因为假设不考虑别的数的影响 我们最少也需要挪动两个数字中间距离-1 那么我们这样贪心的挪动的时候不仅不会i使得其他数字答案增加甚至可能减少

#include<bits/stdc++.h>
using namespace std;
inline char gc(){
    static char now[1<<16],*S,*T;
    if(T==S){T=(S=now)+fread(now,1,1<<16,stdin);if (T==S) return EOF;}
    return *S++;
}
inline int read(){
    int x=0,f=1;char ch=gc();
    while(!isdigit(ch)) {if (ch=='-') f=-1;ch=gc();}
    while(isdigit(ch)) x=x*10+ch-'0',ch=gc();
    return x*f;
}
const int N=220;
int a[N],n,ans;bool flag[N];
int main(){
    freopen("cf.in","r",stdin);
    n=read();n<<=1;
    for (int i=1;i<=n;++i) a[i]=read();
    for (int i=1,pos;i<=n;++i){
        if (flag[a[i]]) continue;
        for (int j=i+1;j<=n;++j){
            if (a[j]==a[i]) {pos=j;break;}
        }
        for (int j=pos;j>i+1;--j) swap(a[j],a[j-1]),++ans;flag[a[i]]=1; 
    }
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值