POJ 1797 Heavy Transportation&&POJ 2253 Frogger 最短路 dijkstra变形

别人的解释感觉很赞


POJ 1797

题意:每条路都有一个重量限制

求从1--n的路径中可通过的最大的重量

思路:

因为是取最大值 所以图的初始化应为-1

d[u]中储存当前路径可以通行的最大质量

更新时比较 先取 路径与前点的最小值 再与当前点比较取最大值(即更新)

#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <limits.h>
#include<algorithm>
#include<math.h>
using namespace std;
#define N 1032
#define INF 1<<20
bool used[N];
int d[N],cost[N][N];
int max(int a,int b)
{return a<b?b:a;}
int min(int a,int b)
{return a>b?b:a;}
void dijkstra(int s,int V){// 邻接矩阵表示  
    for(int i=0;i<=V;i++){//初始化  
        d[i]=cost[0][i];
        used[i]=false; 
    }  
    d[s]=0;  
    while(true){  
        int v=-1; 
		int u; 
		for( u=0;u<V;u++){//取最大的
			if(!used[u]&&(v==-1||d[u]>d[v]))  
				v=u;  
		}  
		if(v==-1)  break;  //顶点全部使用过  
		used[v]=true;  
        for( u=0;u<V;u++){
			d[u]=max(d[u],min(d[v],cost[v][u]));
        }  
    }  
}  
int main()
{
	int cas=1;
	int n,i,j,m;
	int t,a,b,c;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m);
		for(i=0;i<n;i++)
			for(j=0;j<n;j++){//初始化
				cost[i][j]=-1;
				if(i==j)
					cost[i][j]=0;
			}
		for(i=0;i<m;i++){
			scanf("%d%d%d",&a,&b,&c);
			a--,b--;
			if(cost[a][b]<c)
				cost[a][b]=cost[b][a]=c;
		}
		dijkstra(0,n);
		printf("Scenario #%d:\n",cas++);
		printf("%d\n\n",d[n-1]);
	}
	return 0;
}
/*
1
4 5
1 2 1
1 3 3
2 4 2
2 3 4
3 4 3

out 3;
*/

POJ 2253 

与上题类似 求A蛙到B蛙的路径上 每条路径上的边有一个最大值,求这些最大值中的最小值

#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <limits.h>
#include<algorithm>
#include<math.h>
using namespace std;
#define N 1022
bool used[N];
double d[N],cost[N][N];
double max(double a,double b)
{return a<b?b:a;}
double min(double a,double b)
{return a>b?b:a;}
void dijkstra(int s,int V){// 邻接矩阵表示  
    for(int i=0;i<=V;i++){//初始化  
        d[i]=111111110;  
        used[i]=false; 
    }  
    d[s]=0;  
    while(true){  
        int v=-1; 
		int u; 
		// 在未使用过的顶点中选择一个距离最小的顶点  
		for( u=0;u<V;u++){  
			if(!used[u]&&(v==-1||d[u]<d[v]))  
				v=u;  
		}  
		if(v==-1)  break;  //顶点全部使用过  
		used[v]=true;  
        for( u=0;u<V;u++){// 更新从v点能到达的点的最短路  
				d[u]=min(d[u],max(d[v],cost[v][u]));
        }  
    }  
}  
int a[230],b[233];
int main()
{
	int cas=1;
	int n,i,j;
	while(scanf("%d",&n),n)
	{
		memset(cost,0,sizeof(cost));
		for(i=0;i<n;i++)
			scanf("%d%d",&a[i],&b[i]);
		for(i=0;i<n;i++)
			for(j=0;j<n;j++)
				cost[i][j]=sqrt((a[i]-a[j])*(a[i]-a[j])*1.0+(b[i]-b[j])*(b[i]-b[j])*1.0);
		dijkstra(0,n);
		printf("Scenario #%d\n",cas++);
		printf("Frog Distance = %.3lf\n\n",d[1]);
	}
	return 0;
}   
/*
14
4 7
2 1
1 8
2 8
2 7
5 6
1 5
2 5
5 5
4 4
5 4
1 2
3 2
4 1

out 2.236
*/


posted @ 2014-07-09 23:35  kewowlo  阅读(133)  评论(0)    收藏  举报