编程之美--树上的三角形

AC代码。。。

#include<stdio.h>
#include<string>
#include<memory.h>
#include<stdlib.h>
using namespace std;
struct load{
    int dian;
	load*next;
};
int shortload(int start,int juzhen[][105],int dian,load **load_path);
//const int INF=0x3f3f3f3f;
const int INF=10000000;
int visit[105];
int juzhen[105][105];
int dis[105];
int path[105][105];
load * load_path[105];
int main()
{
	int zu,x=1;
	scanf("%d",&zu);
	while(zu--)
	{
		printf("Case #%d:\n",x);
		x++;
		int dian,line,chang;
		int start_x,end_x;
		int i,j,k,l; 
		scanf("%d",&dian);
		for( i=0;i<dian;i++)
			for( j=0;j<dian;j++)
				juzhen[i][j]=INF;

		for(i=0;i<dian-1;i++)
		{
			int start,end;
			scanf("%d%d%d",&start,&end,&chang);
			juzhen[start-1][end-1]=juzhen[end-1][start-1]=chang;
		}
		int ceshi;
		scanf("%d",&ceshi);
		while(ceshi--)
		{
			memset(path,0,105*105*sizeof(int ));
			scanf("%d%d",&start_x,&end_x);
			for( i=0;i<dian;i++)
			{ 
				load_path[i]=(load*)malloc(sizeof(load));
				load_path[i]->dian=start_x-1;
				load* p=(load*)malloc(sizeof(load));
				p->dian=i;
				p->next=NULL;
				load_path[i]->next=p;
			}
			shortload(start_x-1,juzhen,dian,load_path);
			load* p=load_path[end_x-1];
			i=0;
			if(p)
			{
				while(p->next) 
				{
					path[end_x-1][i]=juzhen[p->dian][p->next->dian];
					i++;   
					p=p->next;
				}
			}
			int flag=0;
			if(i<3)
				printf("No\n");
			else 
			{
				for(j=0;j<i-2;j++)
					for( k=j+1;k<i-1;k++) 
						for(l=k+1;l<i;l++)
						{
							if((path[end_x-1][j]+path[end_x-1][k]>path[end_x-1][l])&&(path[end_x-1][j]-path[end_x-1][k]<path[end_x-1][l])
								&&(path[end_x-1][j]+path[end_x-1][l]>path[end_x-1][k])&&(path[end_x-1][j]-path[end_x-1][l]<path[end_x-1][k])
								&&(path[end_x-1][k]+path[end_x-1][l]>path[end_x-1][j])&&(path[end_x-1][k]-path[end_x-1][l]<path[end_x-1][j])
								)
							{
								printf("Yes\n"); 
								flag=1;
								k=i-1;
								j=i-2;
								break;
							}
						}
						if(flag==0)
							printf("No\n");
			}
		}
	}
}
int shortload(int start,int juzhen[][105],int dian,load ** load_path)
{
	for(int i=0;i<dian;i++)
	{
		dis[i]=juzhen[start][i];
		visit[i]=0;
	}
	visit[start]=1;
	dis[start]=0;
	int x=0;
	for(int i=0;i<dian;i++)
	{
		int min=INF;
		for(int j=0;j<dian;j++)
		{
			if(dis[j]<min&&visit[j]==0)
			{
				min=dis[j];
				x=j;
			}
		}
		visit[x]=1;
		for(int j=0;j<dian;j++)
			if(visit[j]==0&&dis[x]+juzhen[x][j]<dis[j])
			{
				load*p=load_path[x]->next;
				while(p)
				{
					load* q=(load*)malloc(sizeof(load));
					q->next=load_path[j]->next;
					load_path[j]->next=q;
					p=p->next;
				}
				p=load_path[x]->next;
				load*q=load_path[j]->next;
				while(p)
				{
					q->dian=p->dian;
					p=p->next;
					q=q->next;
				}
				dis[j]=dis[x]+juzhen[x][j];
			}     
	}
	return 0;
}

 

    原文作者:mikon_lee
    原文地址: https://blog.csdn.net/mikon_lee/article/details/8764744
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞