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;
    }
  • 相关阅读:
    css 旋转
    html 旋转
    链表和数组的区别
    hashmap
    【java开发系列】—— 自定义注解
    java不确定参数个数方法例子
    mysql 删除
    linux下常用命令
    php的几种算法(转载)
    数据容器
  • 原文地址:https://www.cnblogs.com/moonlightpoet/p/5687307.html
Copyright © 2011-2022 走看看