模拟:CF230C

    xiaoxiao2026-09-03  0

    Description You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.

    To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row “00110” one cell to the right, we get a row “00011”, but if we shift a row “00110” one cell to the left, we get a row “01100”.

    Determine the minimum number of moves needed to make some table column consist only of numbers 1.

    Input The first line contains two space-separated integers: n (1 ≤ n ≤ 100) — the number of rows in the table and m (1 ≤ m ≤ 104) — the number of columns in the table. Then n lines follow, each of them contains m characters “0” or “1”: the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table.

    It is guaranteed that the description of the table contains no other characters besides “0” and “1”.

    Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.

    Sample Input Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Hint In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s.

    In the second sample one can’t shift the rows to get a column containing only 1s.

    思路: 枚举每行两个一之间位置到两个一的最小距离,然后将此列上的结果相加,取列中的最小值; 由于这是一个循环,所以注意最后一个一也就是第一个一;

    #include <cstdio> #include <cstring> #include <algorithm> #define inf 0x3f3f3f3f using namespace std; int n,m,l[10009],r[10009]; char mp[109][10009]; int main() { scanf("%d%d",&n,&m); for(int i=0; i<n; i++) scanf("%s",mp[i]); memset(r,0,sizeof r);//保存每一列的结果 int flag=0; for(int i=0; i<n; i++) { memset(l,0,sizeof l);//记录每一个1的位置 for(int j=0; j<m; j++) if(mp[i][j]=='1') l[++l[0]]=j; if(l[0]==0) { flag=1; break; } l[++l[0]]=l[1]+m;//最右边的那一个为左边第一个,由于这是一个循环 for(int j=1; j<l[0]; j++) { int mid=l[j]+l[j+1]>>1; int k=l[j];//枚举两个1中间的点 for(; k<=mid; k++) r[k%m]+=k-l[j];//累加此列在每一行上的结果 for(; k<=l[j+1]; k++) r[k%m]+=l[j+1]-k; } } if(flag) puts("-1"); else { int ans=inf; for(int i=0; i<m; i++) ans=min(ans,r[i]); printf("%d\n",ans); } return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-1311848.html
    最新回复(0)