贪心背后的故事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;
}
发布了40 篇原创文章 · 获赞 6 · 访问量 1410

猜你喜欢

转载自blog.csdn.net/qq_43321732/article/details/104034993