openjudge 4083:我爱北大

题目描述

“红楼飞雪，一时英杰……”耳边传来了那熟悉的歌声。而这，只怕是我最后一次听到这个声音了。

Input

p<=30,Q<=50,R<=20

Sample Input

6
XueYiShiTang
CanYinZhongXin
XueWuShiTang
XueYiXiaoBaiFang
BaiNianJiangTang
GongHangQuKuanJi
6
XueYiShiTang CanYinZhongXin 80
XueWuShiTang CanYinZhongXin 40
XueYiShiTang XueYiXiaoBaiFang 35
XueYiXiaoBaiFang XueWuShiTang 85
CanYinZhongXin GongHangQuKuanJi 60
GongHangQuKuanJi BaiNianJiangTang 35
2
XueYiXiaoBaiFang BaiNianJiangTang
GongHangQuKuanJi GongHangQuKuanJi

Sample Output

XueYiXiaoBaiFang->(35)->XueYiShiTang->(80)->CanYinZhongXin->(60)->GongHangQuKuanJi->(35)->BaiNianJiangTang
GongHangQuKuanJi

注意事项

1.  有重边

#include<iostream>

#include<string>
#include<stack>
using namespace std;

#define MAXV 33
#define INF 1<<29
int v, e;
int g[MAXV][MAXV];
int pre[MAXV][MAXV];
std::string name[MAXV];
stack<int>path;

void floyd(){
int i, j, k;
for (k = 1; k <= v; k++){
for (i = 1; i <= v; i++){
for (j = 1; j <= v; j++){
if (g[i][j] > g[i][k] + g[k][j]){
g[i][j] = g[i][k] + g[k][j];
pre[i][j] = pre[k][j];
}
}
}
}
}
int getIndex(string str){
int i;
for (i = 1; i <= v; i++){
if (str == name[i]){
return i;
}
}
return -1;

}
int main(){
//freopen("in.txt", "r", stdin);
int i, j;
cin >> v;
for (i = 1; i <= v; i++){
for (j = 1; j <= v; j++){
g[i][j] = (i == j ? 0 : INF);
pre[i][j] = -1;
}
}
string str;

/*读入并存入名字*/
for (i = 1; i <= v; i++){
cin >> str;
name[i] = str; //向map中插入数据
}
cin >> e;
string f, t;
int fi, ti;
int w;
for (i = 1; i <= e; i++){
cin >> f >> t >> w; //from to weight

fi = getIndex(f);
ti = getIndex(t);
if (w < g[ti][fi] && w < g[fi][ti]){
g[ti][fi] = g[fi][ti] = w;//双向
pre[fi][ti] = fi;//初始化前驱
pre[ti][fi] = ti;
}// else有重边
}
floyd();

int c;//测试用例
cin >> c;
while (c--){
cin >> f >> t;
fi = getIndex(f);
ti = getIndex(t);
path.push(ti);//压入终点值
int nti;//新的终点值
while (pre[fi][ti] != -1){
ti = pre[fi][ti];
path.push(ti);
}
while (!path.empty()){
fi = path.top();
path.pop();
if (path.size() == 0){
break;
}
ti = path.top();//注意这里不要pop
cout << name[fi] << "->(";
cout << g[fi][ti] << ")->";
}
cout << name[ti];
cout << endl;
}

//fclose(stdin);
//freopen("CON", "r", stdin);
//system("pause");
return 0;

}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120