Til the Cows Come Home
题目描述:
Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.
Farmer John’s field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1…N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.
Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.
特别注意重边问题,WA到哭泣
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct node
{ int id;
int dis;
node(int a=0,int b=0)
{ id=a; dis=b;
}
};
bool operator<(node a,node b)
{ return a.dis>b.dis;
}
int k,n,x,y,dis,a[1001][1001],pd[1001],opt[1001];
priority_queue<node> q;
void djs()
{ q.push(node(1,0));
while(!q.empty())
{ int id,dis;
id=q.top().id; dis=q.top().dis;
q.pop();
if(!pd[id]) opt[id]=dis;
else continue;
pd[id]=1;
for(int i=1;i<=n;i++)
{ if(a[id][i]!=-1&&!pd[i])
q.push(node(i,a[id][i]+dis));
}
}
}
int main()
{
while(cin>>k>>n)
{ memset(pd,0,sizeof(pd));
memset(a,-1,sizeof(a));
for(int i=1;i<=k;i++)
{ cin>>x>>y>>dis;
if((a[x][y]==-1)||(a[x][y]>dis))//判断重边
{ a[x][y]=dis;
a[y][x]=dis;
}
}
djs();
cout<<opt[n]<<endl;
}
return 0;
}
利用优先队列写的迪杰斯特拉,清新脱俗哈哈哈