[hiho]最大集合

题目

题目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;			
}


  

转载于:https://www.cnblogs.com/CongLollipop/p/6839516.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值