zoukankan      html  css  js  c++  java
  • Codeforces Round #363 (Div. 1) B. Fix a Tree 树的拆环

    题目链接:http://codeforces.com/problemset/problem/698/B
    题意:告诉你n个节点当前的父节点,修改最少的点的父节点使之变成一棵有根树。
    思路:拆环。
    题解:http://codeforces.com/blog/entry/46148
    代码:

    #include <cstdio>
    const int maxn = 200200;
    int f[maxn], vis[maxn], n, s, cnt, idx;
    int Find(int x)
    {
        vis[x] = ++ idx;
        while (!vis[ f[x] ])
        {
            x = f[x];
            vis[x] = idx;
        }
        if (vis[ f[x] ] == idx)
        {
            if (s == 0)
                s = x;
            if (f[x] != s)
            {
                f[x] = s;
                cnt ++;
            }
        }
    }
    int main()
    {
        scanf("%d", &n);
        for (int i = 1; i <= n; i ++)
            scanf("%d" , f + i);
        for (int i = 1; i <= n; i ++)
            if (i == f[i])
                s = i;
        for (int i = 1; i <= n; i ++)
            if (!vis[i])
                Find(i);
        printf("%d
    ", cnt);
        for (int i = 1; i <= n; i ++)
            printf("%d ", f[i]);
        return 0;
    }
  • 相关阅读:
    GetArxPath
    动态链接库
    获取文件名称 消除前面的绝对地址路径
    arx 插入图片
    cstring to utf8
    map 用法
    异常处理
    面向对象 "一"
    configparser模块
    装饰器
  • 原文地址:https://www.cnblogs.com/moonlightpoet/p/5687307.html
Copyright © 2011-2022 走看看