PAT 1067 Sort with Swap(0,*)

来源:互联网 发布:网上模拟钢琴软件 编辑:程序博客网 时间:2024/06/08 13:20

这道题调试了好久,代码写的比较丑,总的来说,抓住1. 0是否在0的位置。2 . 一共有几个环。如果0在环内,则需要的交换次数为环中除0外的个数,如果0不在环内,则需要一个交换将0放入。

#include <stdio.h>#include <string.h>#include <iostream>using namespace std;int n,right1,count;int Father[100005];int FindFather(int x){    if (Father[x]!=-1) {        Father[x]=FindFather(Father[x]);        return  Father[x];    }    else        return x;}void Union(int a,int b){    int tempa=FindFather(a);    int tempb=FindFather(b);    if (tempa!=tempb) {        Father[tempa]=tempb;    }}int main(){    int index,ringnum=0;    memset(Father,0xff,sizeof(Father));    //freopen("/Users/pantingting/Documents/code/data/input", "r", stdin);    scanf("%d",&n);    for (int i=0; i<n; i++) {        scanf("%d",&index);        if (index==i) {            Father[i]=-2;            right1++;        }        else            Union(index, i);    }    for (int i=0; i<n; i++) {        if (Father[i]==-1) {            ringnum++;        }    }    int ans=n-right1+ringnum;    if (Father[0]!=-2) {        ans-=2;    }    printf("%d\n",ans);    return 0;}

 

0 0
原创粉丝点击