Advertisement
Abrar_Al_Samit

Collecting Gold (LOJ 1057)

Jul 28th, 2021
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #include <ext/pb_ds/assoc_container.hpp>
  3. #include <ext/pb_ds/tree_policy.hpp>
  4.  
  5. using namespace std;
  6. using namespace __gnu_pbds;
  7.  
  8.  
  9. #define debug(x) cerr << '[' << (#x) << "] = " << x << '\n'
  10.  
  11. template<class T> using ordered_set = tree<T, null_type , less<T> , rb_tree_tag , tree_order_statistics_node_update> ;
  12.  
  13. int N, M;
  14. char g[20][20];
  15. vector<pair<int,int>>gold;
  16. int initx, inity, GN;
  17. int dp[20][20][1<<15];
  18. int dist(int x, int y, int x2, int y2) {
  19.     return max(abs(x-x2), abs(y-y2));
  20. }
  21. int solve(int x, int y, int mask) {
  22.     int& ret = dp[x][y][mask];
  23.     if(ret!=-1) return ret;
  24.     if(mask==(1<<GN)-1) {
  25.         return dist(x, y, initx, inity);
  26.     }
  27.     ret = INT_MAX;
  28.     for(int i=0; i<GN; ++i) if(~mask >> i & 1) {
  29.         ret = min(ret, solve(gold[i].first, gold[i].second, mask|(1<<i)) + dist(x, y, gold[i].first, gold[i].second));
  30.     }
  31.     return ret;
  32. }
  33. void PlayGround(int T) {
  34.     cin >> N >> M;
  35.     for(int i=0; i<N; ++i)
  36.         for(int j=0; j<M; ++j)
  37.             for(int k=0; k<(1<<15); ++k)
  38.                 dp[i][j][k] = -1;
  39.            
  40.        
  41.    
  42.     for(int i=0; i<N; ++i) {
  43.        for(int j=0; j<M; ++j) {
  44.            char& c = g[i][j];
  45.            cin >> c;
  46.            if(c=='x') {
  47.                initx = i, inity = j;
  48.            }
  49.            else if(c=='g') {
  50.                gold.push_back(make_pair(i, j));
  51.            }
  52.        }
  53.     }
  54.     GN = gold.size();
  55.     cout << "Case " << T << ": " << solve(initx, inity, 0) << "\n";
  56.     gold.clear();
  57.  
  58.     #ifndef ONLINE_JUDGE
  59.         cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
  60.     #endif
  61. }
  62. int main() {
  63.     ios_base::sync_with_stdio(0);
  64.     cin.tie(0);
  65.     cout.tie(0);
  66.     #ifndef ONLINE_JUDGE
  67.         freopen("input.txt", "r", stdin);
  68.     #endif
  69.     int T;
  70.     cin >> T;
  71.     for(int i=1; i<=T; ++i)
  72.     PlayGround(i);
  73.  
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement