codility MaxNotPresent

You are playing a game with N cards. On both sides of each card there is a positive integer. The cards are laid on the table. The score of the game is the smallest positive integer that does not occur on the face-up cards. You may flip some cards over. Having flipped them, you then read the numbers facing up and recalculate the score. What is the maximum score you can achieve?

Write a function:

class Solution { public int solution(int[] A, int[] B); }

that, given two arrays of integers A and B, both of length N, describing the numbers written on both sides of the cards, facing up and down respectively, returns the maximum possible score.

For example, given A = [1, 2, 4, 3] and B = [1, 3, 2, 3], your function should return 5, as without flipping any card the smallest positive integer excluded from this sequence is 5.

Given A = [4, 2, 1, 6, 5] and B = [3, 2, 1, 7, 7], your function should return 4, as we could flip the first card so that the numbers facing up are [3, 2, 1, 6, 5] and it is impossible to have both numbers 3 and 4 facing up.

Given A = [2, 3] and B = [2, 3] your function should return 1, as no matter how the cards are flipped, the numbers facing up are [2, 3].

Assume that:

  • N is an integer within the range [1..100,000];
  • each element of arrays A, B is an integer within the range [1..100,000,000];
  • input arrays are of equal size.

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

题目大意:有N个卡片,每个卡片正反都有一个数字,通过反转卡片,使得最小的没有出现在卡片上的数字最大。

1-N这N个数字,每个当作一个节点,如果一个卡片两面分别是a和b,那么a和b连边;如果a和b都大于N,那么该卡片无用;如果a和b有一个大于N,例如a,那么连边b->b,表示只能b这面朝上。建图完成后,一条边代表一个卡片,每一条边可以选择一个节点,代表哪一面朝上,因此对于每个联通集,如果无环也就是树的时候,可以调整成除了最大值之外其他的值都出现过,如果有环,那么所有的值都可以出现。代码来自fanfan。。

#include <bits/stdc++.h>
using namespace std;

const int maxn = 100005;
int N, fa[maxn], vis[maxn], mx[maxn];

int find(int x) {
    return x == fa[x] ? x : fa[x] = find(fa[x]);
}

int solution(vector<int> &A, vector<int> &B) {
    N = A.size();
    for (int i = 1; i <= N; i++) fa[i] = i, vis[i] = 0, mx[i] = i;
    for (int i = 0; i < N; i++) {
        int u = A[i], v = B[i];
        if (u > N && v > N) continue;
        if (u > N) u = v;
        if (v > N) v = u;
        u = find(u);
        v = find(v);
        if (u == v) {
            vis[u] = 1;
        } else {
            fa[u] = v;
            vis[v] |= vis[u];
            mx[v] = max(mx[v], mx[u]);
        }
    }
    int ans = N + 1;
    for (int i = 1; i <= N; i++)
        if (!vis[find(i)]) ans = min(ans, mx[find(i)]);
    return ans;
}

猜你喜欢

转载自blog.csdn.net/KIDGIN7439/article/details/81535229