大模拟真的好难呀
问题:读题不够细,因为一个\0A卡了一个半小时,能做出来已经很不错了!
Tip优化
- 不用结构体,改用三维数组表示会方便很多
- 字符串的处理不够熟悉,单纯为了模拟练习用的char*,改用C++的string会简单很多
- …
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 2000;
#define LL long long
int m, n ,p, q;
struct node{
int R = 0;
int G = 0;
int B = 0;
}Node[N][N],Mean[N*N];
//像素点 R,G,B
//求矩阵范围内的像素均值 容斥原理
void getMean(int x1,int y1, int x2, int y2,int h) // 左上角,右上角
{
// printf("x1:%d,y1:%d,x2:%d,y2:%d\n",x1,y1,x2,y2);
Mean[h].R = (Node[x2][y2].R - Node[x1-1][y2].R - Node[x2][y1-1].R + Node[x1-1][y1-1].R)/(p*q);
Mean[h].G = (Node[x2][y2].G - Node[x1-1][y2].G - Node[x2][y1-1].G + Node[x1-1][y1-1].G)/(p*q);
Mean[h].B= (Node[x2][y2].B - Node[x1-1][y2].B - Node[x2][y1-1].B + Node[x1-1][y1-1].B)/(p*q);
}
int HexToInt(char*a)
{
int m = 0;
int length = strlen(a);
for(int i = 0; i < length; i++)
{
if(a[i]<='9' && a[i]>='0') m = m*16 + a[i]-'0';
else if(a[i]<='z' && a[i]>='a') m = m*16 + a[i]-'a'+10;
else if(a[i]<='Z' && a[i]>='A') m = m*16 + a[i]-'A'+10;
}
return m;
}
void charToRGB(node* nd, char* a)
{
int length = strlen(a);
char b[10];
if(length == 1){
for(int i =0; i<6;i++)
b[i] = a[0];
}
else if(length == 3){
for(int i = 0,m =0; i<6; i+=2)
{
b[i] = a[m];
b[i+1] = a[m++];
}
}
else memcpy(b,a,sizeof b);
char r[3]={0};
char g[3]={0};
char b0[3]={0};
strncpy(r,b,2);
strncpy(g,b+2,2);
strncpy(b0,b+4,2);
nd->R = HexToInt(r);
nd->G = HexToInt(g);
nd->B = HexToInt(b0);
}
void RGBIntToStr(int a)
{
if(a>=100)
{
int num1 = a/100;
a = a%100;
int num2 = a/10;
int num3 = a%10;
printf("\\x3%d\\x3%d\\x3%d",num1,num2,num3);
}else if(a>=10)
{
int num1 = a/10;
int num2 = a%10;
printf("\\x3%d\\x3%d",num1,num2);
}else{
printf("\\x3%d",a);
}
}
int printResult(int h,bool end,bool first)
{
if(Mean[h].R == Mean[h-1].R && Mean[h].G == Mean[h-1].G && Mean[h].B == Mean[h-1].B && !first)
{
if(!end) printf("\\x20");
return 0;
}
else if(Mean[h].R == 0 && Mean[h].G == 0 && Mean[h].B == 0)
{
if(first){
printf("\\x20");
return 0;
}
printf("\\x1B\\x5B\\x30\\x6D");
if(!end) printf("\\x20");
return 0;
}
printf("\\x1B\\x5B\\x34\\x38\\x3B\\x32\\x3B");
RGBIntToStr(Mean[h].R);
printf("\\x3B");
RGBIntToStr(Mean[h].G);
printf("\\x3B");
RGBIntToStr(Mean[h].B);
printf("\\x6D\\x20");
}
int main()
{
cin>>m>>n>>p>>q;
getchar();
/**
*
* m(y)------->
* n(x)
* |
* |
* |
* V
**/
for(int i = 1; i <= n; i ++)
for( int j = 1; j <= m; j ++)
{
char a[8];
scanf("#%s\n",a); // 处理字符到RGB
charToRGB(&Node[i][j],a);
Node[i][j].R = Node[i-1][j].R+Node[i][j-1].R-Node[i-1][j-1].R+Node[i][j].R;
Node[i][j].G = Node[i-1][j].G+Node[i][j-1].G-Node[i-1][j-1].G+Node[i][j].G;
Node[i][j].B = Node[i-1][j].B+Node[i][j-1].B-Node[i-1][j-1].B+Node[i][j].B;
}
// //处理输出
int h=1;
for(int i = 0; i < n/q ; i++) //n/q
{
bool first = true;
for(int j = 0; j< m/p; j++) // m/p
{
int x1 = 1+q*i, y1 =1+j*p, x2 =x1+q-1 , y2 =y1+p-1;
getMean(x1,y1,x2,y2,h);
printResult(h,false,first);
first = false;
h++;
}
printResult(h,true,first);
printf("\\x0A");
}
return 0;
}