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

麻烦各位同学帮忙(kruskal,MLE) 谢谢

Posted by sdie2008140149 at 2010-05-11 19:35:11 on Problem 1258
自己用并查集写的kruskal算法,但总是出现MLE,由于是自己第一次出现这种错误,还请各位同学帮忙看看代码,鄙人认为自己的空间开辟主要是四个数组,但通过计算发现应该不会超过题目的限制,在这个问题上自己肯定有没有注意到的问题,麻烦大家帮忙看看,谢了!



#include <cstdlib>
#include <iostream>
#define maxvernum 100
#include <algorithm>
using namespace std;

struct ArcNode{
	short l;
	short r;
	int weight;
};
short p[maxvernum],rank[maxvernum];//开辟数组空间1
inline void MakeSet (short i){
	p[i]=i;
	rank[i]=0;
}

inline short findSet (short x){
	if (p[x]!=x)
		p[x]=findSet (p[x]);
	return p[x];
}

inline void linkSet (short x,short y){
	if (rank[x]>rank[y])
		p[y]=x;
	else{
		p[x]=y;
		if (rank[x]=rank[y])
			rank[y]++;
	}	
}

inline void unionSet (short x,short y){
	linkSet (findSet(x),findSet(y));
}

bool cmp (ArcNode a,ArcNode b){
	return a.weight<b.weight;	
}

int kruskal (int n,short vernum,ArcNode arrArc[]){
	int k=0,min=0;
	sort (arrArc,arrArc+n,cmp);
	for (int i=0; i<n; i++){
		if (findSet (arrArc[i].l)!=findSet (arrArc[i].r)){
			min+=arrArc[i].weight;
			k++;
			unionSet (arrArc[i].l,arrArc[i].r);
			if (k==vernum-1) break;	
		}	
	}
	return min;
}

int main(int argc, char *argv[])
{
	int vernum;
	while (scanf ("%d",&vernum))
	{
		short *arrVer=new short[vernum];//数组三空间
		for (int i=0;i<vernum;i++)
			MakeSet (i);
		int edgnum=(vernum*(vernum-1))>>1;
		ArcNode *arrArc=new ArcNode[edgnum];//数组四空间
		int dis,k=0;
		for (int i=0;i<vernum;i++)
			for (int j=0;j<vernum;j++)
			{
				cin>>dis;
				if (j>i&&i<vernum)
				{
					arrArc[k].weight=dis;
					arrArc[k].l=i;
					arrArc[k].r=j;
					k++;
				}
			}
		cout<<kruskal (edgnum,vernum,arrArc)<<endl;
	}
    system("PAUSE");
    return EXIT_SUCCESS;
}

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