ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

CF698B Fix a Tree

2020-06-27 09:52:46  阅读:282  来源: 互联网

标签:oth ... ch CF698B Fix getc Tree while isdigit


本题链接

从叶子(尚未访问过的节点)往上找其最远的祖先,若能找到根,则合题;若找到环或找到与树不连通的祖先,则将祖先的父亲指向根。

#include <bits/stdc++.h>
namespace FastIO {
    char buf[1 << 21], buf2[1 << 21], a[20], *p1 = buf, *p2 = buf, hh = '\n';
    int p, p3 = -1;

    void read() {}

    void print() {}

    inline int getc() {
        return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++;
    }

    inline void flush() {
        fwrite(buf2, 1, p3 + 1, stdout), p3 = -1;
    }

    template<typename T, typename... T2>
    inline void read(T &x, T2 &... oth) {
        int f = 0;
        x = 0;
        char ch = getc();
        while (!isdigit(ch)) {
            if (ch == '-')
                f = 1;
            ch = getc();
        }
        while (isdigit(ch)) {
            x = x * 10 + ch - 48;
            ch = getc();
        }
        x = f ? -x : x;
        read(oth...);
    }

    template<typename T, typename... T2>
    inline void print(T x, T2... oth) {
        if (p3 > 1 << 20)
            flush();
        if (x < 0)
            buf2[++p3] = 45, x = -x;
        do {
            a[++p] = x % 10 + 48;
        } while (x /= 10);
        do {
            buf2[++p3] = a[p];
        } while (--p);
        buf2[++p3] = hh;
        print(oth...);
    }
} // namespace FastIO
#define read FastIO::read
#define print FastIO::print
//======================================
using namespace std;
const int maxn=2e5+10;
typedef long long ll;
int n,m,dep[maxn],root,cnt,fa[maxn],ans,in[maxn],t;
void work(int u) {
    dep[u] = ++cnt;
    while (!dep[fa[u]]) {
        u = fa[u];
        dep[u]=cnt;
    }
    if (dep[fa[u]] == cnt) {
        if (root == 0) root = u;
        if (fa[u]!=root){
            ans++;
            fa[u] = root;
        }
    }
}
int main() {
#ifndef ONLINE_JUDGE
    freopen("1.txt", "r", stdin);
    //freopen("2.txt", "w", stdout);
#endif
    //======================================
    read(n);
    for (int i = 1; i <= n; i++) {
        read(fa[i]);
        if (fa[i] == i) root = i;
    }
    for (int i = 1; i <= n; i++) {
        if (!dep[i]) {
            work(i);
        }
    }
    print(ans);
    FastIO::hh = ' ';
    for (int i = 1; i <= n; i++) {
        print(fa[i]);
    }
    //======================================
    FastIO::flush();
    return 0;
}

标签:oth,...,ch,CF698B,Fix,getc,Tree,while,isdigit
来源: https://www.cnblogs.com/Accpted/p/13197409.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有