CodeForces - 1520G To Go Or Not To Go?(bfs)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1520G To Go Or Not To Go?(bfs)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個 n?mn*mn?m 的矩陣,其中:
對于任意兩個傳送門,可以花費其權值和的代價相互到達
也可以花費 www 向上下左右四個方向移動
問從 (1,1)(1,1)(1,1) 到 (n,m)(n,m)(n,m) 的最小花費是多少
題目分析:一開始想到了對傳送門建一個超級源點,將所有傳送門都與超級源點相連然后跑迪杰斯特拉,但是這樣就有 1e71e71e7 條邊,迪杰斯特拉又是超時又是內存超限
分析一下本題的性質,有一個比較重要的點就是,如果是走傳送門的話,肯定只會從一個傳送門進去然后從另一個傳送門出來,因為假如傳送門 AAA 到 BBB 是可行的,那么肯定不會選擇 AAA 到 CCC,然后再從 CCC 到 BBB
所以最小花費只有兩種情況:
基于此,可以用 bfsbfsbfs 計算出所有點到 (1,1)(1,1)(1,1) 的距離和 (n,m)(n,m)(n,m) 的距離,然后枚舉所有的傳送門維護出 AAA 和 BBB 即可
代碼:
// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const LL inf=0x3f3f3f3f3f3f3f3f; const int N=2e3+100; const int b[4][2]={0,1,0,-1,1,0,-1,0}; int n,m,w; int maze[N][N]; LL d1[N][N],d2[N][N]; void bfs(int x,int y,LL d[][N]) {memset(d,-1,sizeof(LL)*(N*N));queue<pair<int,int>>q;q.push({x,y});d[x][y]=0;while(q.size()) {int x,y;tie(x,y)=q.front();q.pop();for(int i=0;i<4;i++) {int xx=x+b[i][0];int yy=y+b[i][1];if(xx<=0||xx>n||yy<=0||yy>m) {continue;}if(maze[xx][yy]==-1||d[xx][yy]!=-1) {continue;}d[xx][yy]=d[x][y]+w;q.push({xx,yy});}} } int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);read(n),read(m),read(w);for(int i=1;i<=n;i++) {for(int j=1;j<=m;j++) {read(maze[i][j]);}}bfs(1,1,d1);bfs(n,m,d2);LL ans=inf;if(d1[n][m]!=-1) {ans=min(ans,d1[n][m]);}LL res1=inf,res2=inf;for(int i=1;i<=n;i++) {for(int j=1;j<=m;j++) {if(maze[i][j]>0) {if(d1[i][j]!=-1) {res1=min(res1,d1[i][j]+maze[i][j]);}if(d2[i][j]!=-1) {res2=min(res2,d2[i][j]+maze[i][j]);}}}}ans=min(ans,res1+res2);if(ans==inf) {puts("-1");return 0;}write(ans);return 0; }總結
以上是生活随笔為你收集整理的CodeForces - 1520G To Go Or Not To Go?(bfs)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1521D N
- 下一篇: CodeForces - 1517D E