P10933 创世纪 贪心题解

洛谷题目传送门

看了这道题的题解,都是用 dp 写的,在这里献上一篇贪心做法。

贪心做法

基于拓扑排序的思想,可以先把所有入度为 0 0 0 的点放入队列中。

对于队列中的的每一个点:

(记这个点为 t t t,下个点为 a [ t ] a[t] a[t]

  1. 试图将 t t t 其变为“上帝手中的点”,则 a [ t ] a[t] a[t] 将被放入星球,所以使 a n s + 1 ans+1 ans+1
  2. 标记 t t t a [ t ] a[t] a[t] 已经遍历过了。
  3. a [ a [ t ] ] a[a[t]] a[a[t]] 的入度 − 1 -1 1,若它的入度被减为 0 0 0,并且没有被遍历过,表明它能成为新的“上帝手中的点”,将它加入队列。

现在,能被我们贪的点已经全部贪完了,剩下的点构成了若干个环。而对于每一个环,其中每两个点可以能再放一个进入星球。
所以先求出每个环的大小,再将换的大小乘 2 2 2 统计入答案即可

AC 代码

#include <iostream>
#include <queue>
using namespace std;

typedef long long ll;

const int N = 1145141;

// 快读
void read(int &x) {
    x = 0;
    char ch = getchar();
    while (ch < '0' || ch > '9') ch = getchar();
    while (ch >= '0' && ch <= '9') {
        x = (x << 3) + (x << 1) + ch - 48;
        ch = getchar();
    }
}
int tmp[100];
// 快写
void write(int x) {
    int cnt = 0;
    while (x > 0) {
        tmp[++cnt] = x % 10;
        x /= 10;
    }
    while (cnt > 0) {
        putchar(tmp[cnt] + 48);
        --cnt;
    }
    putchar('\n');
}

int n, a[N], b[N], ans = 0;
bool vis[N];
queue<int> q;

void bfs() {
    int t;
    while (!q.empty()) {
        t = q.front();
        q.pop();
        
        vis[t] = true;
        if (!vis[a[t]]) {
            ans++;
            vis[a[t]] = true;
            if (--b[a[a[t]]] == 0 && !vis[a[a[t]]]) {
                q.push(a[a[t]]);
            }
        }
    }
}

int main() {
    read(n);
    for (int i = 1; i <= n; ++i) {
        read(a[i]);
        b[a[i]]++;
    }
    for (int i = 1; i <= n; ++i) {
        if (b[i] == 0) q.push(i);
    }

    //先贪
    bfs();

    //统计剩下的每个环的大小
    int k, cnt;
    for (int i = 1; i <= n; ++i) {
        if (!vis[i]) {
            k = i;
            vis[k] = true;
            cnt = 1;
            while (!vis[a[k]]) {
                k = a[k];
                vis[k] = true;
                cnt++;
            }
            ans += cnt >> 1;
        }
    }
    write(ans);
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值