题目描述 Description
现在是晚餐时间,而母牛们在外面分散的牧场中。 农民约翰按响了电铃,所以她们开始向谷仓走去。 你的工作是要指出哪只母牛会最先到达谷仓(在给出的测试数据中,总会有且只有一只最快的母牛)。 在挤奶的时候(晚餐前),每只母牛都在她自己的牧场上,一些牧场上可能没有母牛。 每个牧场由一条条道路和一个或多个牧场连接(可能包括自己)。 有时,两个牧场(可能是字母相同的)之间会有超过一条道路相连。 至少有一个牧场和谷仓之间有道路连接。 因此,所有的母牛最后都能到达谷仓,并且母牛总是走最短的路径。 当然,母牛能向着任意一方向前进,并且她们以相同的速度前进。 牧场被标记为’a’..’z’和’A’..’Y’,在用大写字母表示的牧场中有一只母牛,小写字母中则没有。 谷仓的标记是’Z’,注意没有母牛在谷仓中。
注意’m’和’M’不是同一个牧场否则错误上面的意思是说:输入数据中可能会同时存在M,m(郁闷ing),比如
M a a m m z
输入描述 Input Description
第 1 行: 整数 P(1<= P<=10000),表示连接牧场(谷仓)的道路的数目。
第 2 ..P+1行: 用空格分开的两个字母和一个整数:
被道路连接牧场的标记和道路的长度(1<=长度<=1000)。
输出描述 Output Description
单独的一行包含二个项目:最先到达谷仓的母牛所在的牧场的标记,和这只母牛走过的路径的长度。
样例输入 Sample Input
5
A d 6
B d 3
C e 9
d Z 8
e Z 3
样例输出 Sample Output
B 11
分析
就是读入稍微注意一下就好,剩下就是模板啦。
代码
#include <bits/stdc++.h>
using namespace std;
struct lx
{
int x,ly;
};
priority_queue <lx> dl;
const bool operator < (const lx x,const lx y)
{
return x.x > y.x ;
}
int head[200],nxt[30000],to[30000],wei[30000],dis[200];
int sum,minn = 999999999,minx,p,w,tot;
bool vis[200];
char tp1[5],tp2[5];
const int oo = 999999999;
void cr(int x,int y,int w)
{
sum++;
nxt[sum] = head[x];
head[x] = sum;
to[sum] = y;
wei[sum] = w;
}
void dij(int s)
{
memset(vis,false,sizeof(vis));
memset(dis,0x1f,sizeof(dis));
dis[s] = 0;
lx tp;
tp.x = 0;
tp.ly = s;
dl.push(tp);
while(!dl.empty())
{
lx ftp = dl.top();
dl.pop();
if(vis[ftp.ly])
continue;
vis[ftp.ly] = true;
for (int o = head[ftp.ly]; o; o = nxt[o])
{
if (!vis[to[o]])
if (wei[o] + dis[ftp.ly] < dis[to[o]])
{
dis[to[o]] = wei[o] + dis[ftp.ly];
lx fftp;
fftp.ly = to[o];
fftp.x = dis[to[o]];
dl.push(fftp);
}
}
}
return;
}
int main()
{
scanf("%d",&p);
for (int i = 1;i <= p;i++)
{
scanf("%s%s%d",tp1,tp2,&w);
cr(tp1[0],tp2[0],w);
cr(tp2[0],tp1[0],w);
}
dij('Z');
for (int i = 'A';i <= 'Y';i++)
{
if (dis[i] < minn)
{
minn = dis[i];
minx = i;
}
}
tp1[0] = minx;
printf("%s %d\n",tp1,minn);
return 0;
}