牛客周赛91 D题(数组4.0) 题解

原题链接

https://ac.nowcoder.com/acm/contest/108038/D

题目描述

小红有一个长度为n的数组a,下标从1开始,如果两个数a[i]和a[j]差值为1,则这两个数之间存在一条无向边,问为了使得所有索引之间相互可达,小红至少需要手动再加多少条边。

解题思路

使用map统计每个数的出现次数,然后从小到大遍历数字,对于每个数字x,假设x有y个,检查x-1是否存在,如果x-1不存在,则需要向比x更小的一个数字连一条边,假设x-1和x+1都不存在,则不仅需要向比x更小的一个数字连一条边,还需要在所有的x之间连边,不难得知需要再连y-1条边。详见代码。

代码(CPP)

#include 
using namespace std;
using ll = long long;
using ull = unsigned long long;
#define endl "\n"
const int maxn = 2e5 + 10;
const ll INF = 0x3f3f3f3f3f3f3fLL;
int a[maxn];

void solve() {
    int n;
    cin >> n;
    map<int, int> mp;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        mp[a[i]]++;
    }
    int ans = 0;
    for (auto x : mp) {
        if (!mp.count(x.first - 1)) {
            ans++;
            if (!mp.count(x.first + 1)) {
                ans += x.second - 1;
            }
        }
    }
    cout << ans - 1 << endl;
}

int main() {
//     freopen("in.txt", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cout << fixed;
    cout.precision(18);

    int t;
    cin >> t;
    while (t--)
        solve();
    return 0;
}

你可能感兴趣的:(算法&数据结构,算法竞赛,算法,数据结构,STL,牛客周赛,map)