标签:
Description
The Little Elephant loves to play with color cards.
He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).
Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.
Input
The first line contains a single integer n(1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card.
The numbers in the lines are separated by single spaces.
Output
On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.
Sample Input
3
4 7
4 7
7 4
0
5
4 7
7 4
2 11
9 7
1 1
2
题目意思:
翻拍子的游戏,,正反面有1e9种颜色,当相同的颜色朝向上的个数大于 (n + 1)/2大,就是funny
求翻拍子最少几次,变成funny。
思路分析:
用正常思路一直超时,,唉,,看了别人的才懂。。
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; struct node { int x; int m; // 记录正面反面 }s[201000]; bool cmp(node a,node b) { return a.x < b.x; } int main() { int n; while(cin >> n) { int k = 0; int a, b; for(int i = 0; i < n; i++) { scanf("%d%d", &a, &b); if(a != b) { s[k].x = a; s[k++].m = 0; s[k].x = b; s[k++].m = 1; } else { s[k].x = a; s[k++].m = 0; } } sort(s, s + k, cmp); // 从小到大 int l = -1, ans = 0; int i, j = 0; for(i = 0; i < k; i = j) { if(s[i].m)// 判断正反面 ans = 0;// 反面 else ans = 1;//正 for(j = i + 1; j < k && s[i].x == s[j].x; j++) if(s[j].m == 0)// 判断正面相同多少个 ans++; if(j - i >= (n + 1) / 2) { if(ans >= (n + 1) / 2) { l = 0; i = k; j = k; break; } else { if(l == -1) l = (n + 1) / 2 - ans; else l = min(l, (n + 1) / 2 - ans); } } } printf("%d\n",l); } return 0; } /* 使用结构体数组,记录每张牌的正面和反面的颜色, 并记录他们处于正面还是反面,然后再使用sort对颜色大小排序, 之后遍历所有颜色,当某种颜色出现次数>=n/2时,这样就找到满足情况的颜色, 依次类推,找到最小的情况即可。 特殊注意:有些牌的正面颜色和反面颜色相同, 那么只需要记录其正面即可。还有当某个颜色处于正面的次数>=n/2时, 直接输出0即可。 */
练习题目 4 Little Elephant and Cards
标签:
原文地址:http://www.cnblogs.com/lyf-acm/p/5444716.html