Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdio>
- #include <queue>
- #include <cstring>
- #define task "FAIR"
- using namespace std;
- using ll = long long;
- using ld = long double;
- const int N = 1e3 + 2;
- int m, n, k;
- int a[N][N], l[N][N], r[N][N];
- int x[] = {-1, 0, 1, 0}, y[] = {0, 1, 0, -1};
- int dis[N][N];
- const int Inf = 1e9 + 7;
- void Read(){
- cin >> m >> n >> k;
- for(int i = 1; i <= m; ++i)
- for(int j = 1; j <= n; ++j)
- cin >> a[i][j];
- }
- void Init(){
- for(int i = 1; i <= m; ++i)
- fill_n(dis[i], N, Inf),
- dis[i][1] = a[i][1];
- }
- struct Tque{
- int x, y, w, z;
- Tque() {}
- Tque(int m, int n, int p, int q){
- x = m;
- y = n;
- w = p;
- z = q;
- }
- bool Valid(){
- return dis[x][y] == w;
- }
- bool operator < (const Tque& a) const{
- return w > a.w
- ||(w == a.w && z < a.z);
- }
- };
- bool Relax(const Tque& s, const int& x, const int& y){
- if(x > m || x < 1 || y > n || y < 1)
- return false;
- int res = s.w + (s.z != 0 ? 0 : a[x][y]);
- if(dis[x][y] > res ){
- dis[x][y] = res;
- return true;
- }
- return false;
- }
- pair<int, int> Dijkstra(){
- Init();
- priority_queue<Tque> s;
- for(int i = 1; i <= m; ++i)
- s.push(Tque(i, 1, dis[i][1], (a[i][1] == 0) * k));
- while(s.size()){
- Tque c = s.top();
- s.pop();
- //cerr << c.y << "\n";
- if(!c.Valid())
- continue;
- if(c.y == n)
- return {c.x, c.y};
- for(int i = 0; i < 4; ++i)
- if(Relax(c, c.x + x[i], c.y + y[i])){
- int u = c.x + x[i], v = c.y + y[i];
- s.push(Tque(u, v, dis[u][v], a[u][v] == 0 ? k : max(0, c.z - 1)));
- l[u][v] = c.x;
- r[u][v] = c.y;
- }
- }
- }
- void trace(int x, int y){
- if(l[x][y] == 0 || r[x][y] == 0){
- cout << x << " " << y << "\n";
- return;
- }
- trace(l[x][y], r[x][y]);
- cout << x << " " << y << "\n";
- }
- void Solve(){
- pair<int, int> s = Dijkstra();
- cout << dis[s.first][s.second] << "\n";
- trace(s.first, s.second);
- }
- main(){
- ios::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0); if(fopen(task".INP", "r"))
- freopen(task".INP", "r", stdin),
- freopen(task".OUT", "w", stdout);
- Read();
- Solve();
- }
Advertisement
Add Comment
Please, Sign In to add comment