题目:http://poj.org/problem?id=1009
AC代码(C++):
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
#include <math.h>
using namespace std;
struct PAIR{
int ccc;
int num;
};
struct POINT{
int ccc;
int r;
int c;
};
int n;
vector<PAIR> input;
vector<POINT> needToCa;
vector<PAIR> output;
long long pointCount;
int rowCount;
int getC(int r,int c){
long long pos = r*n + c;
long long startPos = 0;
for(vector<PAIR>::iterator it = input.begin(); it != input.end(); it++){
if(startPos<=pos&&startPos+it->num>pos)return it->ccc;
startPos += it->num;
}
}
int getCCC(int r, int c){
int rtn = 0;
for(int i=r-1;i<=r+1;i++){
for(int j=c-1;j<=c+1;j++)
{
if(i<0||i>=rowCount||j>=n||j<0||(i==r&&j==c))continue;
int temp = abs(getC(i,j)-getC(r,c));
if(rtn<temp)rtn=temp;
}
}
return rtn;
}
bool cmp(POINT a, POINT b){
if(a.r!=b.r)return a.r<b.r;
else return a.c<b.c;
}
int main(){
for(;;){
cin>>n;
if(n==0)break;
//输入
for(;;){
PAIR tmppair;
cin>>tmppair.ccc>>tmppair.num;
if(tmppair.ccc!=0||tmppair.num!=0){
input.push_back(tmppair);
pointCount+=tmppair.num;
}
else{
input.push_back(tmppair);//这是个坑
break;
}
}
rowCount = pointCount/n;
//计算关键像素点
long long startPos = 0;
for(vector<PAIR>::iterator it = input.begin(); it != input.end(); it++){
int tmpr;
int tmpc;
tmpr = startPos/n;
tmpc = startPos%n;
for(int i = tmpr-1; i <= tmpr+1; i++){
for(int j = tmpc-1; j <= tmpc+1; j++){
if(i>=0&&i<rowCount&&j>=0&&j<n){
POINT tmppoint;
tmppoint.r = i;
tmppoint.c = j;
tmppoint.ccc = getCCC(i,j);
needToCa.push_back(tmppoint);
}
}
}
startPos += it->num;
}
//排序
sort(needToCa.begin(),needToCa.end(),cmp);
//输出
cout<<n<<endl;
vector<POINT>::iterator temp = needToCa.begin();
for(vector<POINT>::iterator it = needToCa.begin(); it != needToCa.end(); it++)
{
if(it->ccc==temp->ccc)
continue;
printf("%d %d\n",temp->ccc,it->r*n+it->c-temp->r*n-temp->c);
temp=it;
}
printf("%d %d\n",temp->ccc,pointCount-temp->r*n-temp->c);
cout<<"0 0\n";
//清理
input.clear();
needToCa.clear();
output.clear();
pointCount = 0;
}
cout<<"0\n";
}
总结:
1.像如此大规模的模拟题暴力肯定不能解决, 需要找规律. 而这题的规律是每个颜色-数量对(PAIR)的起始像素和它周围的8个像素可能是输出PAIR的起始位置. 也就是说, 只要计算所有输入PAIR的起始像素及其周围像素(即关键像素)的输出颜色, 除此之外的像素颜色就等于它们前面最近的关键像素点的颜色.
2.最后输入的0 0不能忽略, 也要放进去计算. 具体看下面这个例子
3
10 8
0 1
0 0