#include using namespace std; int height[201][201]; int alien[9][2]; int my[2]; int shortestPath[201][201]; bool alr[201][201]; bool obh[201][201]; int n, k; ofstream fout("invaders.out"); ifstream fin("invaders.in"); void dijkstra(int x, int y, int curr) { if(obh[y][x]) return; //cout << x << " " << y << " " << curr << endl; shortestPath[y][x] = alr[y][x]?min(shortestPath[y][x], curr):curr; alr[y][x] = true; if(x < n-1) { obh[y][x] = true; //cout << "r" << endl; dijkstra(x+1, y, curr+(height[y][x+1] 0) { obh[y][x] = true; //cout << "l" << endl; dijkstra(x-1, y, curr+(height[y][x-1] 0) { obh[y][x] = true; //cout << "u" << endl; dijkstra(x, y-1, curr+(height[y-1][x]> n >> k; for(int i = 0; i < n; i ++) { for(int j = 0; j < n; j ++) { fin >> height[i][j]; } } fin >> my[0] >> my[1]; my[0]--; my[1]--; for(int i = 0; i < k; i ++) { fin >> alien[i][0] >> alien[i][1]; alien[i][0]--; alien[i][1]--; } dijkstra(my[1], my[0], 0); int ans = shortestPath[alien[0][0]][alien[0][1]]; int far = 0; int last = 0; for(int i = 1; i < k; i ++) { for(int a = 0; a < n; a ++) { for(int j = 0; j < n; j ++) { alr[a][j] = false; obh[a][j] = false; } } //cout << shortestPath[alien[i][0]][alien[i][1]] << endl; dijkstra(my[1], my[0], 0); if(shortestPath[alien[i][0]][alien[i][1]] < ans) last = i; ans = min(ans, shortestPath[alien[i][0]][alien[i][1]]); } //cout << last << endl; while(far != k-1) { int nlast; int tm = 1000000; for(int i = 0; i < k; i ++) { for(int a = 0; a < n; a ++) { for(int j = 0; j < n; j ++) { alr[a][j] = false; obh[a][j] = false; } } //cout << shortestPath[alien[i][0]][alien[i][1]] << endl; if(last != i){dijkstra(alien[last][1], alien[last][0], 0); if(shortestPath[alien[i][0]][alien[i][1]] < tm) nlast = i; tm = min(shortestPath[alien[i][0]][alien[i][1]],tm); } } last = nlast; ans+=tm; far++; } fout << ans << endl; }