一个人的旅行
Time Limit : 1000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 45 Accepted Submission(s) : 21
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Input
接着有T行,每行有三个整数a,b,time,表示a,b城市之间的车程是time小时;(1=<(a,b)<=1000;a,b 之间可能有多条路)
接着的第T+1行有S个数,表示和草儿家相连的城市;
接着的第T+2行有D个数,表示草儿想去地方。
Output
Sample Input
6 2 3 1 3 5 1 4 7 2 8 12 3 8 4 4 9 12 9 10 2 1 2 8 9 10
Sample Output
9
#include <iostream>
#include <queue>
#include <cstdio>
#define INF 1000000
#define MAXN 1005
using namespace std;
struct ArcNode
{
int to;
int weight;
ArcNode *next;
};
queue<int> Q;
int n,m;
int map[MAXN][MAXN];
ArcNode *List[MAXN];
int inq[MAXN];
int dist[MAXN],path[MAXN];
void SPFA(int src)
{
int i,u;
ArcNode *temp;
for(i=1;i<=n;i++)
{
dist[i]=INF;path[i]=src;inq[i]=0;
}
dist[src]=0;path[src]=src;inq[src]++;
Q.push(src);
while(!Q.empty())
{
u=Q.front();Q.pop();inq[u]--;
temp=List[u];
while(temp!=NULL)
{
int v=temp->to;
if(dist[v]>dist[u]+temp->weight)
{
dist[v]=dist[u]+temp->weight;path[v]=u;
if(!inq[v]){Q.push(v);inq[v]++;}
}
temp=temp->next;
}
}
}
int main(int argc, char *argv[])
{
int i,j;
int ss[MAXN],dd[MAXN];
int u,v,w;
int t,s,d;
while(cin>>t>>s>>d)
{
n=0;
memset(List,0,sizeof(List));
memset(map,0,sizeof(map));
ArcNode *temp;
for(i=0;i<t;i++)
{
scanf("%d%d%d",&u,&v,&w);
if(u>n) n=u;
if(v>n) n=v;
if(map[u][v]==0||w<map[u][v])
{
map[u][v]=map[v][u]=w;
temp=new ArcNode;
temp->to=v;temp->weight=w;temp->next=NULL;
if(List[u]==NULL) List[u]=temp;
else {temp->next=List[u];List[u]=temp;}
temp=new ArcNode;
temp->to=u;temp->weight=w;temp->next=NULL;
if(List[v]==NULL) List[v]=temp;
else {temp->next=List[v];List[v]=temp;}
}
}
for(i=0;i<s;i++) cin>>ss[i];
for(i=0;i<d;i++) cin>>dd[i];
int min=INF;
for(i=0;i<s;i++)
{
SPFA(ss[i]);
for(j=0;j<d;j++)
{
if(min>dist[dd[j]]) min=dist[dd[j]];
}
}
for(j=0;j<n;j++)
{
temp=List[j];
while(temp!=NULL)
{
List[j]=temp->next;delete temp;temp=List[j];
}
}
cout<<min<<endl;
}
return 0;
}