CF 873C Strange Game On Matrix(貪心)
題目:
Strange Game On MatrixIvan is playing a strange game.
He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:
- Initially Ivan‘s score is 0;
- In each column, Ivan will find the topmost 1 (that is, if the current column is j, then he will find minimum i such that ai, j = 1). If there are no 1‘s in the column, this column is skipped;
- Ivan will look at the next min(k, n - i
Of course, Ivan wants to maximize his score in this strange game. Also he doesn‘t want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.
The first line contains three integer numbers n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100).
Then n lines follow, i-th of them contains m integer numbers — the elements of i-th row of matrix a. Each number is either 0 or 1.
OutputPrint two numbers: the maximum possible score Ivan can get and the minimum number of replacements required to get this score.
Examples input4 3 2output
0 1 0
1 0 1
0 1 0
1 1 1
4 1input
3 2 1output
1 0
0 1
0 0
2 0Note
In the first example Ivan will replace the element a1, 2.
題解:先求出每列的前綴和,然後每列模擬題意去求出能夠得到的最大分數,並記錄前面消掉多少1。最後相加。
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 5 const int N=111; 6 int M[N][N]; 7 int sum[N][N]; 8 9 int main(){ 10 int n,m,k,t,res1=0,res2=0; 11 cin>>n>>m>>k; 12 for(int i=1;i<=n;i++) 13 for(int j=1;j<=m;j++) 14 cin>>M[i][j],sum[i][j]=M[i][j]; 15 16 for(int i=1;i<=m;i++) 17 for(int j=1;j<=n;j++) 18 sum[j][i]+=sum[j-1][i]; 19 20 for(int i=1;i<=m;i++){ //column 21 int cnt=-1,ans=0,tmp=0; 22 for(int j=1;j<=n;j++){ //row 23 if(M[j][i]==1){ 24 t=min(k,n-j+1); 25 cnt++; 26 int tt=sum[j+t-1][i]-sum[j][i]+1; 27 if(tt>tmp) tmp=tt,ans=cnt; 28 } 29 } 30 res1+=tmp;res2+=ans; 31 } 32 33 cout<<res1<<" "<<res2<<endl; 34 35 return 0; 36 }
CF 873C Strange Game On Matrix(貪心)