[Codeforces Round #492 (Div. 1) ][B. Suit and Tie]

http://codeforces.com/problemset/problem/995/B

题目大意:给一个长度为2*n的序列,分别有2个1,2,3,...n,相邻的位置可以进行交换,求使所有相同的数字相邻的最少交换次数.(n<100)

题目分析:n的数据范围特别小,所以只需要想到合理的(贪心)移动方式直接模拟即可,可以从左往右进行遍历,遍历到每个位置时,都把在这个位置之后且与这个数字相同的数字移动到它的旁边直接模拟即可(之所以正确是因为这样移动会使两个相同元素之间的元素都往后移动一次,由于是从左到右遍历,所以这些元素往后移动会减少以后移动的次数).

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<queue>
 5 using namespace std;
 6 typedef long long ll;
 7 int qwq[205],a[205];
 8 int main(){
 9     //freopen("in.txt","r",stdin);
10     int n;
11     cin>>n;
12     for(int i=0;i<2*n;i++){
13         scanf("%d",&qwq[i]);
14         a[qwq[i]]=i;
15     }
16     int ans=0;
17     for(int i=0;i<2*n;i++){
18         if(a[qwq[i]]>i+1){
19         for(int j=i+1;j<a[qwq[i]];j++){
20             if(a[qwq[j]]>a[qwq[i]])ans--;
21         }
22         ans+=a[qwq[i]]-i-1;
23         }
24     }
25     cout << ans << endl;
26     return 0;
27 }
View Code

猜你喜欢

转载自www.cnblogs.com/MekakuCityActor/p/9954667.html