生活随笔
收集整理的这篇文章主要介绍了
[蓝桥杯]算法提高 道路和航路(spfa+deque+快读优化)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
问题描述
农夫约翰正在针对一个新区域的牛奶配送合同进行研究。他打算分发牛奶到T个城镇(标号为1…T),这些城镇通过R条标号为(1…R)的道路和P条标号为(1…P)的航路相连。
每一条公路i或者航路i表示成连接城镇Ai(1<=A_i<=T)和Bi(1<=Bi<=T)代价为Ci。每一条公路,Ci的范围为0<=Ci<=10,000;由于奇怪的运营策略,每一条航路的Ci可能为负的,也就是-10,000<=Ci<=10,000。
每一条公路都是双向的,正向和反向的花费是一样的,都是非负的。
每一条航路都根据输入的Ai和Bi进行从Ai->Bi的单向通行。实际上,如果现在有一条航路是从Ai到Bi的话,那么意味着肯定没有通行方案从Bi回到Ai。
农夫约翰想把他那优良的牛奶从配送中心送到各个城镇,当然希望代价越小越好,你可以帮助他嘛?配送中心位于城镇S中(1<=S<=T)。
输入格式
输入的第一行包含四个用空格隔开的整数T,R,P,S。
接下来R行,描述公路信息,每行包含三个整数,分别表示Ai,Bi和Ci。
接下来P行,描述航路信息,每行包含三个整数,分别表示Ai,Bi和Ci。
输出格式
输出T行,分别表示从城镇S到每个城市的最小花费,如果到不了的话输出NO PATH。
样例输入
6 3 3 4
1 2 5
3 4 5
5 6 10
3 5 -100
4 6 -100
1 3 -10
样例输出
NO PATH
NO PATH
5
0
-95
-100
数据规模与约定
对于20%的数据,T<=100,R<=500,P<=500;
对于30%的数据,R<=1000,R<=10000,P<=3000;
对于100%的数据,1<=T<=25000,1<=R<=50000,1<=P<=50000。
思路:
这本来是最短路的一道模板题,但是太扯淡了,弄了很久。
坑点:
①有负数边,得用spfa。
②边数特别大,所以得优化一下,我用的deque+快读优化。
③空间不要开小了,开小了会超时。。
但是就算是这样,在dotcpp网站上还是没有过去,得分95。在蓝桥杯官网的网站上以421ms过的。
代码如下:
#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std
;const int maxx
=1e5+10;
const int maxm
=1e6+10;
struct edge
{int to
,next
,w
;
}e
[maxx
<<6];
int head
[maxx
<<6],dis
[maxx
],vis
[maxx
],num
[maxx
];
int n
,r
,p
,s
,tot
;inline void init()
{tot
=0;memset(head
,-1,sizeof(head
));
}
inline void add(int u
,int v
,int w
)
{e
[tot
].to
=v
,e
[tot
].next
=head
[u
],e
[tot
].w
=w
,head
[u
]=tot
++;
}
inline void spfa()
{memset(dis
,inf
,sizeof(dis
));memset(vis
,0,sizeof(vis
));memset(num
,0,sizeof(num
));dis
[s
]=0;vis
[s
]=1;deque
<int> q
;q
.push_front(s
);while(q
.size()){int u
=q
.front();q
.pop_front();vis
[u
]=0;for(int i
=head
[u
];i
!=-1;i
=e
[i
].next
){int to
=e
[i
].to
;if(dis
[to
]>dis
[u
]+e
[i
].w
){dis
[to
]=dis
[u
]+e
[i
].w
;if(vis
[to
]==0){vis
[to
]=1;if(q
.empty())q
.push_front(to
);else{if(dis
[to
]>dis
[q
.front()]) q
.push_back(to
);else q
.push_front(to
);}}}}}
}
inline int read()
{int s
= 0, w
= 1; char ch
= getchar();while(ch
< '0' || ch
> '9'){ if(ch
== '-') w
= -1; ch
= getchar();}while(ch
>= '0' && ch
<= '9') s
= s
* 10 + ch
- '0', ch
= getchar();return s
* w
;
}
int main()
{n
=read(),r
=read(),p
=read(),s
=read();init();int x
,y
,z
;for(int i
=1;i
<=r
;i
++){x
=read();y
=read();z
=read();add(x
,y
,z
);add(y
,x
,z
);}for(int i
=1;i
<=p
;i
++){x
=read();y
=read();z
=read();add(x
,y
,z
);}spfa();for(int i
=1;i
<=n
;i
++){if(dis
[i
]==inf
) printf("NO PATH\n");else printf("%d\n",dis
[i
]);}return 0;
}
(本来想用deque+LLL优化一下呢,结果优化还不如不优化。。可能LLL不适合这道题目吧。)
努力加油a啊,(o)/~
总结
以上是生活随笔为你收集整理的[蓝桥杯]算法提高 道路和航路(spfa+deque+快读优化)的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。