Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define task "MOVE"
- #include <iostream>
- #include <cstdio>
- #include <vector>
- using namespace std;
- constexpr int N = 1e4 + 5;
- constexpr int Inf = 1e9 + 7;
- int n, m, c[102][N];
- char a[102][N * 3];
- void Read()
- {
- cin >> n >> m;
- for (int i = 1; i <= n; ++i)
- for (int j = 1; j <= m; ++j)
- {
- cin >> a[i][j];
- a[i][j + m] = a[i][j + m * 2] = a[i][j];
- }
- }
- void Subtask_2()
- {
- for (int i = 1; i <= n; ++i)
- for (int j = 1; j <= m; ++j)
- {
- c[i][j] = Inf;
- for (int t = 1; t <= m; ++t)
- if (a[i][t] == '1')
- c[i][j] = min(c[i][j], min((j - t + m) % m, (t - j + m) % m));
- }
- }
- void Subtask_3()
- {
- for (int i = 1; i <= n; ++i)
- {
- vector<int> one;
- for (int j = 1; j <= m * 3; ++j)
- if (a[i][j] == '1')
- one.emplace_back(j);
- if (one.empty()) // Không có cách nào để chọn cho một ô trong hàng này
- {
- for (int j = 1; j <= m; ++j)
- c[i][j] = Inf;
- }
- else
- {
- for (int j = 1; j <= m; ++j)
- {
- int t = lower_bound(one.begin(), one.end(), j + m) - one.begin();
- c[i][j] = min(one[t] - (j + m), (j + m) - one[t - 1]);
- }
- }
- }
- }
- void Print()
- {
- int ans(Inf);
- for (int i = 1; i <= m; ++i)
- {
- int tmp(0);
- for (int j = 1; j <= n; ++j)
- {
- tmp += c[j][i];
- if (tmp >= Inf)
- tmp = Inf;
- }
- ans = min(ans, tmp);
- }
- cout << (ans >= Inf ? -1 : ans);
- }
- int32_t 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();
- if (m <= 1000)
- Subtask_2();
- else
- Subtask_3();
- Print();
- }
Add Comment
Please, Sign In to add comment