第二次熬夜做题,发现这一次的阅读量好大,英语差的连题目都看不懂。。。好不容易看懂了一个,代码写了我两个小时,哎.....不解释了。
CF比赛连接 Codeforces Round #141 (Div. 2)
B题 给你两个矩阵,元素全部是 0 或 1,然后问你如何重叠矩阵使得重叠部分的对应乘积和最大(这就是那个求和公式的意思)。
又是跟矩阵有关系,前几天看矩阵还不太清楚,这回就要写了。。。还好题目不是很难,算法神马的没有啥特别之处,矩阵才50*50,所以暴力即可,只是元素转换的时候要注意下标越界并且要对应相乘。总的来说算一个模拟题,自己代码能力稍差,费时太多。
#include <stdio.h> #include <string.h> #include <iostream> using namespace std; const int MAX = 51; int m1[MAX][MAX]; int m2[MAX][MAX]; void Input(int m[][MAX],int a,int b){ for (int i = 0; i < a ; i++){ for (int j = 0 ; j < b ; j++){ scanf("%1d",&m[i][j]); } } } int CalcMatrix(int an,int am, int bn,int bm, int y,int x){ // y行 x列 // Matrix(a)n*m {->pos(x,y)} * Matrix(b)n*m int res = 0; for (int j = 0 ; j < bm ; j++){ for (int i = 0; i < bn ; i++){ if ( (i + x >= 0 && j + y >= 0) ){ if (m1[i][j] == 1 && m2[i + x][j + y] == 1){ res++; } } } } return res; } int main() { #define TEST_INFILE_ #ifdef TEST_INFILE freopen("in.txt","r",stdin); #endif memset(m1,-1,sizeof(m1)); memset(m2,-1,sizeof(m2)); int a1,b1,a2,b2; cin >> a1 >> b1; Input(m1,a1,b1); cin >> a2 >> b2; Input(m2,a2,b2); int max = -1; int xx=0,yy=0; for (int x = -(b1 - 1) ; x <= b2 - 1; x++){ for (int y = -(a1 - 1) ; y <= a2 - 1 ; y++){//up down int temp = CalcMatrix(a2,b2,a1,b1,x,y); if (temp > max){ xx = y; yy = x; max = temp; } } } cout << xx << " " << yy << endl; return 0; } /* test data 8 6 1 1 1 0 1 1 1 0 0 1 0 1 1 1 0 1 0 1 1 0 0 1 0 1 1 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 2 3 0 0 1 1 1 0 == -5 -3 add_ans = 3 3 2 01 10 00 2 3 001 111 == 0 1 add_ans = 2 3 3 000 010 000 1 1 1 == -1 -1 add_ans = 1 */