1)这道题有很多需要学习的地方,除了code技巧上的运用比如链表存储边、初始化、结构体构造函数,在思维上也有很多比如判断走哪个点除了花费以外还加了对停留次数的判断、而停留次数可能大于城市个数(对于查询数据做一个鲁棒性的判断)等等。后来再做仍然容易出错,值得经常复习。
#include <iostream>
#include <string.h>
#include <map>
#include <queue>
#include <stdio.h>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxm=120;
const int maxx=10020;
//vector<int> citys[maxm];//第二维不定长,边的花费
int inque[maxm][maxm];//是否在队列,!!注意也是二维的,还有时间不同编号相同也是不同情况
map <string,int>name;//注意及时清空
int cost[maxm][maxm];//边到边的花费
int head[maxm];
int dis[maxm][maxm];//第i个地方总共第j次停留的花费,注意j是总停留第几次而不是在这个点第几次停留的情况
int len;
struct Edge
{
int from;
int to;
int value;
int next;//该边的出发点的上一条边
} edge[maxx];
struct node
{
int num;
int time;
node(int n,int t)
{
num=n; //构造函数
time=t;
}
};
void add(int from,int to,int value)
{
edge[len].from=from;
edge[len].to=to;
edge[len].value=value;
edge[len].next=head[from];
head[from]=len;
len++;
}
void SPFA(int star,int endd,int n)
{
node ss(star,0);
queue <node> q;
q.push(ss);
inque[star][0]=1;
dis[star][0]=0;
while(!q.empty()){
node cur=q.front();
inque[cur.num][cur.time]=0;
q.pop();
for(int i=head[cur.num];i!=-1;i=edge[i].next){
int to=edge[i].to;
if(dis[to][cur.time+1]>dis[cur.num][cur.time]+edge[i].value){//这里的dis里第二维表示次数,用cur.time+1是巧妙的事情
dis[to][cur.time+1]=dis[cur.num][cur.time]+edge[i].value;
if(inque[to][cur.time+1]==0){
q.push(node(to,cur.time+1));
inque[to][cur.time+1]=1;
}
}
}
}
}
int main()
{
int kase;
cin>>kase;
for(int ll=1; ll<=kase; ll++)
{
//初始化
len=0;
memset(head,-1,sizeof(head));
memset(cost,INF,sizeof(cost));
memset(inque,0,sizeof(inque));
memset(dis,INF,sizeof(dis));//dis[maxn][maxn]里面的值,第一维用到n即可,第二位用到n-1即可(因为最多停留n-1次,此刻应该想到停留次数问题,所以最后会有鲁棒性的处理)。
int n;
scanf("%d",&n);
name.clear();
string a;
for(int i=1; i<=n; i++)
{
cin>>a;
name[a]=i;
}
int star=name["Calgary"];
int endd=name["Fredericton"];
int m;
cin>>m;
string b;
int c;
for(int i=1; i<=m; i++)
{
cin>>a>>b>>c;
add(name[a],name[b],c);
}
SPFA(star,endd,n);
int que;
int stop;
cin>>que;
if(ll!=1)
{
cout<<endl;
}
printf("Scenario #%d\n",ll);
for(int i=1; i<=que; i++)
{
cin>>stop;
stop++;//代码中到达终点也算停留一次了
if(stop>n-1)//要有鲁棒性!数据里的停留次数有大于城市个数的存在,如果不加这步判断,就会WA
{
stop=n-1;//!!!!!!!
}
int ans=INF;
for(int j=1;j<=stop;j++){
ans=min(ans,dis[endd][j]);
}
if(ans<INF)
{
printf("Total cost of flight(s) is $%d\n",ans);
}
else
{
cout<<"No satisfactory flights\n";
}
}
}
return 0;
}
2)
http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=25133