Problem-d-Codeforces Fix a Tree

Source: Internet
Author: User

Problem-d-Codeforces Fix a Tree

After reading the first name of the code, suddenly wake up ...

I can take all the individual points as lines, then only the lines and loops.

If all lines, the number of direct lines-1, is the operand.

If there is a ring and a line, the ring is opened at the same time, connected to the line. That is the total number of lines and rings-1.

If only the ring, put all the rings open, mutual access, total need n operations.

#include <cstdio>#include<algorithm>using namespacestd;Const intMAXN = 2e5+5;intCUR[MAXN];intPRE[MAXN];intFind (intx) {returnPRE[X] = = x?X:find (pre[x]);}intMain () {intN; scanf ("%d",&N); intThread =0; intAns =0;  for(inti =1; i<=n; i++) Pre[i] =i;  for(inti =1; i<=n; i++) {scanf ("%d",&Cur[i]); if(cur[i]==i) {thread=i; Ans++; }        Else        {            intFX =Find (i); intFY =Find (Cur[i]); if(FX = =FY) {Cur[i]=i; Ans++; }            Else{PRE[FX]=fy; }        }    }    if(thread==0)//It's all rings .    {         for(inti =1; i<=n; i++)        {            if(cur[i]==i) {thread=i;  Break; }} ans++; } printf ("%d\n", ans-1);  for(inti =1; i<=n; i++)    {        if(cur[i]==i) Cur[i] =thread; }     for(inti =1; i<n; i++) printf ("%d", Cur[i]); printf ("%d\n", Cur[n]); return 0;}

Problem-d-Codeforces Fix a Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.