我感觉这题没什么好说的,就是坑人啊,这数据怎么想都有问题,他给的n条路里面居然可能不包括起点和终点
别问我怎么知道的,我这么写的代码wa了得十遍,不包括起点和终点,题干你为什么不告诉我一声呢???
然后这道题思路其实不难,如何把字符串转换成数字标记,即把数字与字符串联系起来便于最短路的遍历,不难想到map,如果不是有坑肯定一遍过了。。。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
using namespace std;
#define inf 0x3f3f3f3f
int mapp[162][162];
int cnt;
void init()
{
for(int i = 1; i <= 160; i ++)
for(int j = 1; j <= 160; j ++)
{
if(i == j)mapp[i][j] = 0;
else mapp[i][j] = inf;
}
}
int main()
{
int n;
map<string,int>m;
string a, b;
int temp;
int f;
while(scanf("%d",&n)!=EOF)
{
if(n == -1)break;
cnt = 3;
f = 0;
init();
m.clear();
cin>>a>>b;
if(a == b)f=1;
m[a] = 1;
m[b] = 2;
while(n --)
{
cin>>a>>b;
scanf("%d",&temp);
if(!m[a])
m[a] = cnt++;
if(!m[b])
m[b] = cnt++;
if(mapp[m[a]][m[b]] > temp)
mapp[m[b]][m[a]] = mapp[m[a]][m[b]] = temp;
}
for(int k = 1; k <= cnt; k ++)
for(int i = 1; i <= cnt; i ++)
for(int j = 1; j <= cnt; j ++)
{
if(mapp[i][j] > mapp[i][k] + mapp[k][j])
mapp[i][j] = mapp[i][k] + mapp[k][j];
}
if(mapp[1][2] < inf)
printf("%d\n",mapp[1][2]);
else if(f == 1)
printf("0\n");
else
printf("-1\n");
}
return 0;
}
错误的代码在这里,别进坑了,越想越难受
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
using namespace std;
#define inf 0x3f3f3f3f
int mapp[205][205];
int cnt;
int n;
map<string,int>m;
string a, b;
string c, d;
int temp;
void init()
{
for(int i = 1; i <= 200; i ++)
for(int j = 1; j <= 200; j ++)
{
if(i == j)mapp[i][j] = 0;
else mapp[i][j] = inf;
}
cnt = 1;
m.clear();
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
if(n == -1)break;
init();
cin>>c>>d;//坑在这里
while(n --)
{
cin>>a>>b;
cin>>temp;
if(m[a] == 0)
m[a] = cnt++;
if(m[b] == 0)
m[b] = cnt++;
if(mapp[m[a]][m[b]] > temp)
mapp[m[b]][m[a]] = mapp[m[a]][m[b]] = temp;
}
for(int k = 1; k < cnt; k ++)
for(int i = 1; i < cnt; i ++)
for(int j = 1; j < cnt; j ++)
{
if(mapp[i][j] > mapp[i][k] + mapp[k][j])
mapp[i][j] = mapp[i][k] + mapp[k][j];
}
if(mapp[m[c]][m[d]] < inf)
cout<<mapp[m[c]][m[d]]<<endl;
else
cout<<-1<<endl;
}
return 0;
}