只想到了暴力的方法,时间复杂度是O(n^3),最后一个测试点过不去。
网上看到了动态规划的方法,见http://www.byvoid.com/blog/usaco-334-home-on-the-range/。
感觉递推关系式还是很不容易想到的。当然,想到就很简单了。
代码如下:
/*
ID: thestor1
LANG: C++
TASK: range
*/
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cassert>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
const int N = 250;
int square[N][N];
int main()
{
FILE *fin = fopen ("range.in", "r");
FILE *fout = fopen ("range.out", "w");
//freopen("log.txt", "w", stdout);
int n;
fscanf(fin, "%d\n", &n);
char c;
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n;)
{
fscanf(fin, "%c", &c);
if(c == '0' || c == '1')
{
square[i][j] = c - '0';
j++;
}
}
}
for(int i = n - 2; i >= 0; --i)
{
for(int j = n - 2; j >= 0; --j)
{
if(square[i][j])
{
square[i][j] = 1 + min(min(square[i + 1][j], square[i][j + 1]), square[i + 1][j + 1]);
}
}
}
int cnt[N + 1] = {0};
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
cnt[square[i][j]]++;
}
}
for(int i = N - 1; i >= 2; --i)
{
cnt[i] += cnt[i + 1];
}
for(int i = 2; i <= N; ++i)
{
if(!cnt[i])
{
break;
}
fprintf(fout, "%d %d\n", i, cnt[i]);
}
return 0;
}