路径数组变为统计数组

来源:互联网 发布:sql2005数据库复制 编辑:程序博客网 时间:2024/05/22 04:55
/** * Created by lxw, liwei4939@126.com on 2017/11/5. * 路径数组变为统计数组 * 给定一个路径数组paths,paths[i] == j表示城市i指向城市j, * 若paths[i] == i,则表示城市i是首都 * 设计函数调整paths为统计数组nums,nums[i] == j表示距离为i的城市有j座 * 首都的距离为1,即nums[0] ==1 */public class pathsToCount {    public void pathsToDistances(int[] paths){        int cap = 0;        for (int i=0; i< paths.length; i++){            if(paths[i] == i){                cap = i;            } else if(paths[i] > -1){                int curI = paths[i];                paths[i] = -1;                int preI = i;                while (paths[curI] != curI){                    if(paths[curI] > -1){                        int nextI = paths[curI];                        paths[curI] = preI;                        preI = curI;                        curI = nextI;                    } else {                        break;                    }                }                int value = paths[curI] == curI ? 0: paths[curI];                while (paths[preI] != -1){                    int lastPreI = paths[preI];                    paths[preI] = --value;                    curI = preI;                    preI = lastPreI;                }                paths[preI] = --value;            }        }        paths[cap] = 0;    }    public void distanceToNums(int[] disArr){        for (int i=0; i< disArr.length; i++){            int index = disArr[i];            if(index < 0){                disArr[i] = 0;                while (true){                    index = -index;                    if(disArr[index] > -1){                        disArr[index]++;                        break;                    } else {                        int nextIndex = disArr[index];                        disArr[index] = 1;                        index = nextIndex;                    }                }            }        }        disArr[0] = 1;    }    public void pathsToNums(int[] paths){        if(paths == null || paths.length == 0){            return;        }        // citiiesPath -> distanceArray        pathsToDistances(paths);        // distanceArray -> numArray        distanceToNums(paths);    }    public static void main(String[] args){        pathsToCount tmp = new pathsToCount();        int[] paths = {9, 1, 4, 9, 0, 4, 8, 9, 0, 1};        tmp.pathsToNums(paths);        for (int lel : paths){            System.out.print(lel + " ");        }        System.out.println();    }}