1. 程式人生 > >[hiho]最大集合

[hiho]最大集合

++ limit bre tor int 結果 string port 單點

題目

題目1 : 最大集合

時間限制:10000ms 單點時限:1000ms 內存限制:256MB

描述

給定一個1-N的排列A[1], A[2], ... A[N],定義集合S[K] = {A[K], A[A[K]], A[A[A[K]]] ... }。

顯然對於任意的K=1..N,S[K]都是有限集合。

你能求出其中包含整數最多的S[K]的大小嗎?

輸入

第一行包含一個整數N。(1 <= N <= 100000)

第二行包含N個兩兩不同的整數,A[1], A[2], ... A[N]。(1 <= A[i] <= N)

輸出

最大的S[K]的大小。

樣例輸入
7  
6 5 1 4 2 7 3
樣例輸出
4

暴力解法 結果超時了。

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * Created by aolie on 2017/5/7.
 */
public class Main {

    public static void main(String args[]){

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int [] A = new int[N];
        for(int i=0;i<N;i++){
            A[i] = sc.nextInt();
        }
        System.out.print(help(N,A));

    }

    public static int help(int N, int [] A){
        
        int res =0;
        int temp =0;
    
        for(int k=1;k<=N;k++){
            temp = A[k-1];
            Set<Integer> myset = new HashSet<>();
             while(temp<=N&&temp>=1&&myset.add(temp)){
                myset.add(temp);
                temp = A[temp-1];
            }
            res = Math.max(res,myset.size());   
         
        }

     return res;

    }
}

 優化: 用set來記錄遍歷的狀態,若發現遍歷過了 即刻返回

public static int  help(int N,int [] A){
       Set<Integer> myset = new HashSet<>();
       int res=0;
       for(int i=1;i<=N;i++){
    	   int j=i;
    	   if(myset.contains(j))
    	         continue;
    	   Set<Integer> temp = new HashSet<>();
    	   while(A[j]<=N){
    		   if(temp.contains(j)||myset.contains(j))
    			   break;
    		   temp.add(j);
    		   j =A[j];
    	   }
    	   Iterator inte = temp.iterator();
    	    for(int k=0;k<temp.size()-1;k++)
    	    	myset.add((Integer) inte.next());
    	   res = Math.max(res,temp.size());
    	   
       }	
		return res;			
}


  

[hiho]最大集合