A - Little Elephant and Cards CodeForces - 205D

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.

Examples
Input
3
4 7
4 7
7 4
Output
0
Input
5
4 7
7 4
2 11
9 7
1 1
Output
2
Note
In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.

In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.

题意:
每个卡牌正面反面有颜色,初始均为正面。可以将一些卡牌翻面。求使得所有卡牌正面均为同一种颜色的最小操作次数。

思路:
枚举每种颜色正面多少个,反面多少个(正反面颜色相同就当做只有正面)。再枚举最终正面颜色为哪个即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include <map>
#include <unordered_map>

using namespace std;
typedef long long ll;

const int maxn = 2e5 + 7;
unordered_map<int,int>mp;

int a[maxn],b[maxn];//正面和背面每种颜色数量

int main() {
    int n;scanf("%d",&n);
    int cnt = 0;
    for(int i = 1;i <= n;i++) {
        int x,y;scanf("%d%d",&x,&y);
        if(!mp[x]) {
            mp[x] = ++cnt;
        }
        if(!mp[y]) {
            mp[y] = ++cnt;
        }
        x = mp[x];y = mp[y];
        a[x]++;
        if(x != y) b[y]++;
    }
    int ans = 1e9,half = (n + 1) / 2;
    for(int i = 1;i <= cnt;i++) {
        if(a[i] >= half) {
            ans = min(ans,0);
        } else if(a[i] + b[i] < half) {
            continue;
        } else {
            int num = half - a[i];
            ans = min(ans,num);
        }
    }
    if(ans == 1e9) {
        printf("-1\n");
    } else {
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tomjobs/article/details/107847858