POJ 1135 (邻接表DIJKSTRA) 错误代码

诶。。思路极端不清晰的情况下选择邻接表来写这题。。写一半才发现用矩阵会好很多。。

好吧。。一会改用矩阵。。

失败的代码贴出:

#include <stdio.h>
#include <string.h>
#define MAXN 510
#define inf 1000000000
int n,m;

double value[MAXN*MAXN];
int head[MAXN],next[MAXN*MAXN],point[MAXN*MAXN];
int tot;

int dist[MAXN],used[MAXN],prev[MAXN];

int print[MAXN];
int printcount;

int used2[MAXN];

int casecount;

void addedge(int a, int b, double len)
{
	point[tot]=b;
	value[tot]=len;
	next[tot]=head[a];
	head[a]=tot++;
}

void dijkstra(int src)
{
	for (int i=0; i<n ;i++) {
		used[i]=0;
		dist[i]=inf;
		prev[i]=-1;
	}
	
	dist[src]=0;
	
	for (int i=0; i<n; i++) {
		
		int min=inf,minp=-1;
		
		for (int j=0; j<n; j++) {
			if(!used[j] && dist[j]<min) {
				minp=j;
				min=dist[j];
			}
		}
		
		if(min==inf) break;
		
		used[minp]=1;
		
		int idx=head[minp];
		while (~idx) {
			if (!used[point[idx]] && value[idx] < dist[point[idx]]) {
				dist[point[idx]] = value[idx];
				prev[point[idx]] = minp;
			}
			idx=next[idx];
		}
	}
	
}

int a, b;
double len;

int main()
{
	casecount=1;
	while(scanf("%d%d",&n,&m),m) {
		
		memset(print,0,sizeof(print));
		memset(head,-1,sizeof(head));
		memset(next,-1,sizeof(next));
		memset(used2,0,sizeof(used2));
		tot=0;
		
		for(int i=0; i<m; i++) {
			scanf("%d%d%lf",&a,&b,&len);
			addedge(a-1,b-1,len);
			addedge(b-1,a-1,len);
		}
		
		dijkstra(0);
		
		int maxdist1p;
		
		double maxdist1=0;
		for (int i=0; i<n; i++)
			if(dist[i]>maxdist1) {
				maxdist1=dist[i];
				maxdist1p=i;
			}
		
		double maxdist2=0;
		int maxdist2l;
		int maxdist2r;
		
		for (int i=0; i<n; i++) {
			int idx=head[i];
			used2[i]=1;
			while(~idx) {
				if(!used2[point[idx]] && (dist[i]+dist[point[idx]]+value[idx])/2 > maxdist2) {
					maxdist2=(dist[i]+dist[point[idx]]+value[idx])/2;
					maxdist2l=i;
					maxdist2r=point[idx];
				}
				idx=next[idx];
			}
		}
		
		if(n==1) maxdist1p=0;
		
		if (maxdist2==maxdist1) {
			printf("System #%d\nThe last domino falls after %.1f seconds, at key domino %d.\n\n",casecount++,maxdist1,maxdist1p+1);
		}
		else {
			printf("System #%d\nThe last domino falls after %.1f seconds, between key dominoes %d and %d.\n\n",casecount++,maxdist2,maxdist2l+1,maxdist2r+1);
		}
		/*
		printcount=0;
		
		for (int i=0; i<n; i++) {
			if (dist[i]==maxdist) {
				printcount++;
				print[i]=1;
			}
		}
		
		if(printcount==1) {
			printf("System #%d\nThe last domino falls after %.1f seconds, at key domino ");
			for(int i=0;i<n;i++) {
				if(print[i]=1)
					printf("%d.\n",i);
			}
		}
		*/
	}
}
posted on 2011-07-18 17:26  Eucalyptus  阅读(245)  评论(0编辑  收藏  举报