贪心背后的故事Codeforces 995B(Suit and Tie)

题目:
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 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 (1≤n≤100), the number of pairs of people.

The second line contains 2n integers a1,a2,…,a2n. For each i with 1≤i≤n, i appears exactly twice. If aj=ak=i, that means that the j-th and 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.
题意:
有n对数字,分别是1~n,现在进行操作,这个操作为将任意相邻的两个数交换,问最少进行多少次之后可以使每一对数字都在一起。
思路
这题由于数据比较小,暴力扫一遍就好(代码为暴力代码)。在数据范围较大的情况下,通过查资料,得知了另一种做法,使用树状数组,贪心来做。

#include<iostream>
using namespace std;
const int maxn = 1e2 + 5;
int a[maxn * 2];
int main()
{
	int n; cin >> n;
	n *= 2;
	for (int i = 1; i <= n; i++)
		cin >> a[i];
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		if (a[i]) {
			int j;
			for (j = i + 1; ; j++) {
				if (a[j] != a[i] && a[j] != 0)
					ans += 1;
				else if(a[j] == a[i])
					break;
			}
			a[j] = 0;
		}
	}
	cout << ans << endl;
	return 0;
}
全部评论

相关推荐

09-29 15:34
已编辑
北京航空航天大学 C++
做个有文化的流氓:结果是好的,过程不重要,而且你的offer太多了
软开人,秋招你打算投哪些...
点赞 评论 收藏
分享
牛客48826091...:哥们胸肌挺好看
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务