Problem 2261 浪里个浪
链接:http://acm.fzu.edu.cn/problem.php?pid=2261
Accept: 15 Submit: 31
Time Limit: 1500 mSec Memory Limit : 32768 KB
Problem Description
TonyY是一个喜欢到处浪的男人,他的梦想是带着兰兰姐姐浪遍天朝的各个角落,不过在此之前,他需要做好规划。
现在他的手上有一份天朝地图,上面有n个城市,m条交通路径,每条交通路径都是单行道。他已经预先规划好了一些点作为旅游的起点和终点,他想选择其中一个起点和一个终点,并找出从起点到终点的一条路线亲身体验浪的过程。但是他时间有限,所以想选择耗时最小的,你能告诉他最小的耗时是多少吗?
Input
包含多组测试数据。
输入第一行包括两个整数n和m,表示有n个地点,m条可行路径。点的编号为1 - n。
接下来m行每行包括三个整数i, j, cost,表示从地点i到地点j需要耗时cost。
接下来一行第一个数为S,表示可能的起点数,之后S个数,表示可能的起点。
接下来一行第一个数为E,表示可能的终点数,之后E个数,表示可能的终点。
0<S, E≤n≤100000,0<m≤100000,0<cost≤100。
Output
输出他需要的最短耗时。
Sample Input
4 4
1 3 1
1 4 2
2 3 3
2 4 4
2 1 2
2 3 4
Sample Output
1
Source
福州大学第十四届程序设计竞赛_重现赛
题目大意:有n个点,m条边,有s个可能的起点,有m个可能的终点。
问:从任一个起点出发,到任一个终点,时间最短是多少?
思路:普通的求最短路的方法,只能求一个起点到多个终点的最短路(这道题将所有的起点全部遍历一边也能过),所以要从新建立一个点,这个点到所有起点的距离都是0,这样点1到点2的距离就是dp[点2]-dp[点1],求出最短的距离,就行了。
#include<stdio.h>
#include<string.h>
#include<queue>
#define inf 0x3f3f3f3f
#include<algorithm>
using namespace std;
int a[100009];//存所有的起点
int xia[100009];//
int dp[100009];
int first[100009];
struct node
{
int s,e;
int p;
int next;
} edge[100009];
int N;
void build(int s,int e,int p)
{
edge[N].s=s;
edge[N].e=e;
edge[N].p=p;
edge[N].next=first[s];
first[s]=N;
N++;
}
void spfa(int x,int n)
{
for(int i=0; i<=n; i++)
{
dp[i]=inf;
xia[i]=0;
}
xia[x]=1;
dp[x]=0;
queue<int>q;
q.push(x);
while(!q.empty())
{
x=q.front();
q.pop();
xia[x]=0;
for(int i=first[x]; i!=-1; i=edge[i].next)
{
if(dp[edge[i].e]>edge[i].p+dp[x])
{
dp[edge[i].e]=edge[i].p+dp[x];
if(xia[edge[i].e]==0)
{
q.push(edge[i].e);
xia[edge[i].e]=1;
}
}
}
}
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
int s,e,q;
N=0;
memset(first,-1,sizeof(first));
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&s,&e,&q);
build(s,e,q);
}
int n_s;
scanf("%d",&n_s);
for(int i=0;i<n_s;i++)//起点
{
scanf("%d",&a[i]);
build(0,a[i],0);//创建一个新的点
}
spfa(0,n);
int n_e;
scanf("%d",&n_e);
int f;
int max_=inf;
for(int i=0;i<n_e;i++)//终点
{
scanf("%d",&f);
for(int j=0;j<n_s;j++)
{
if(dp[f]-dp[a[j]]<max_)
max_=dp[f]-dp[a[j]];
}
}
printf("%d\n",max_);
}
return 0;
}