Dang_Quan_10_Tin

MOVE 27.12.2021

Dec 27th, 2021 (edited)
914
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #define task "MOVE"
  2.  
  3. #include <iostream>
  4. #include <cstdio>
  5. #include <vector>
  6.  
  7. using namespace std;
  8.  
  9. constexpr int N = 1e4 + 5;
  10. constexpr int Inf = 1e9 + 7;
  11. int n, m, c[102][N];
  12. char a[102][N * 3];
  13.  
  14. void Read()
  15. {
  16.     cin >> n >> m;
  17.  
  18.     for (int i = 1; i <= n; ++i)
  19.         for (int j = 1; j <= m; ++j)
  20.         {
  21.             cin >> a[i][j];
  22.             a[i][j + m] = a[i][j + m * 2] = a[i][j];
  23.         }
  24. }
  25.  
  26. void Subtask_2()
  27. {
  28.     for (int i = 1; i <= n; ++i)
  29.         for (int j = 1; j <= m; ++j)
  30.         {
  31.             c[i][j] = Inf;
  32.             for (int t = 1; t <= m; ++t)
  33.                 if (a[i][t] == '1')
  34.                     c[i][j] = min(c[i][j], min((j - t + m) % m, (t - j + m) % m));
  35.         }
  36. }
  37.  
  38. void Subtask_3()
  39. {
  40.     for (int i = 1; i <= n; ++i)
  41.     {
  42.         vector<int> one;
  43.         for (int j = 1; j <= m * 3; ++j)
  44.             if (a[i][j] == '1')
  45.                 one.emplace_back(j);
  46.  
  47.         if (one.empty()) // Không có cách nào để chọn cho một ô trong hàng này
  48.         {
  49.             for (int j = 1; j <= m; ++j)
  50.                 c[i][j] = Inf;
  51.         }
  52.         else
  53.         {
  54.             for (int j = 1; j <= m; ++j)
  55.             {
  56.                 int t = lower_bound(one.begin(), one.end(), j + m) - one.begin();
  57.                 c[i][j] = min(one[t] - (j + m), (j + m) - one[t - 1]);
  58.             }
  59.         }
  60.     }
  61. }
  62.  
  63. void Print()
  64. {
  65.     int ans(Inf);
  66.  
  67.     for (int i = 1; i <= m; ++i)
  68.     {
  69.         int tmp(0);
  70.         for (int j = 1; j <= n; ++j)
  71.         {
  72.             tmp += c[j][i];
  73.             if (tmp >= Inf)
  74.                 tmp = Inf;
  75.         }
  76.  
  77.         ans = min(ans, tmp);
  78.     }
  79.  
  80.     cout << (ans >= Inf ? -1 : ans);
  81. }
  82.  
  83. int32_t main()
  84. {
  85.     ios::sync_with_stdio(0);
  86.     cin.tie(0);
  87.     cout.tie(0);
  88.     if (fopen(task ".INP", "r"))
  89.     {
  90.         freopen(task ".INP", "r", stdin);
  91.         freopen(task ".OUT", "w", stdout);
  92.     }
  93.  
  94.     Read();
  95.     if (m <= 1000)
  96.         Subtask_2();
  97.     else
  98.         Subtask_3();
  99.  
  100.     Print();
  101. }
  102.  
Add Comment
Please, Sign In to add comment