Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

克鲁斯卡尔TLE,好心人帮看看吧

Posted by xuchang at 2010-08-02 12:53:39 on Problem 2485 and last updated at 2010-08-02 12:54:18
克鲁斯卡尔一直TLE。。。。。这个算法也能优化吗?


import java.util.*;
public class Main
{
    static int[][] adj;
    static int min=99999999;
    static int total;
    static boolean[] bl;
	public static void main(String[] args)
	{
		int mini=0,minj=0,count;
		int ans;
		Scanner cin=new Scanner(System.in);
		int st=cin.nextInt();
		while(st--!=0)
		{
		  total=cin.nextInt();
		  count=total-2;
		  ans=0;
		  adj=new int[total][total];
		  bl=new boolean[total];
		  min=99999999;
		  for(int i=0;i<total;i++)
			  for(int j=0;j<total;j++)
			  {
				  adj[i][j]=cin.nextInt();
				  if(adj[i][j]<min&&adj[i][j]!=0)
				  {
					  min=adj[i][j];
					  mini=i;
					  minj=j;
				  }
			  }
		  adj[mini][minj]=99999999;
		  min=99999999;
		  while(count--!=0)
		  {
			  for(int i=0;i<total;i++)
					  for(int j=i;j<total;j++)
						  if(adj[i][j]<min&&adj[i][j]!=0)
						  {
							  min=adj[i][j];
							  mini=i;
							  minj=j;
						  } //当前最小边
			  ans=min;
			  min=99999999;
			  adj[mini][minj]=99999999;
			  boolean flag=true;
			  for(int l=0;l<total;l++) bl[l]=false;
			  for(int l=0;l<total;l++)
				  if((adj[mini][l]==99999999||adj[l][mini]==99999999))
					  if(!dfs(l,mini))
					  {
						  flag=false;
						  break;
					  }
			  if(flag)
			  {
			  }
			  else
			  {
				 adj[mini][minj]=0;
			     count++;
			  }
		  }
		  System.out.println(ans);
		  cin.nextLine();
		}
	}
	
	public static boolean dfs(int m,int n)  //判断是否有环路
	{
		bl[m]=true;
		for(int l=0;l<total;l++)
		{
			if(!bl[l]&&(l!=n)&&(adj[m][l]==99999999||adj[l][m]==99999999))
			{
				if(adj[l][n]==99999999||adj[n][l]==99999999) 
				{
					 return false;
				}

				if(!dfs(l,n))
					return false;

			}
		} 
		bl[m]=false;
		return true;
	}
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator