您的位置:首页 > 编程语言 > Java开发

usaco Home on the Range java ---DP

2012-09-15 23:37 561 查看
/*
ID: daniel.20
LANG: JAVA
TASK: range
*/

import java.util.*;
import java.io.*;

public class range {
static int[][] table = new int[300][300];
static int num;
static int[][] result = new int[300][300];
static int[] res = new int[300];

static void dp() throws IOException{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("range.out")));
for(int i=1;i<=num;i++){
for(int j=1;j<=num;j++){
if(table[i][j] == 1)
result[i][j] = Math.min(result[i-1][j-1], Math.min(result[i-1][j], result[i][j-1]))+1;
for(int k=2;k<=result[i][j];k++)
res[k]++;
}
}

for(int i=2;i<=num;i++){
if(res[i]!=0) {
out.println(i+" "+res[i]);
}
}
out.close();
}
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("range.in"));
num = Integer.parseInt(reader.readLine());
for(int i=1;i<=num;i++){
String s = reader.readLine();
for(int j=1;j<=num;j++){
table[i][j] = s.charAt(j-1)-'0';
}
}
dp();
}
}


Test 1: TEST OK [0.065 secs, 274688 KB]
Test 2: TEST OK [0.065 secs, 274688 KB]
Test 3: TEST OK [0.065 secs, 274688 KB]
Test 4: TEST OK [0.072 secs, 274688 KB]
Test 5: TEST OK [0.072 secs, 274688 KB]
Test 6: TEST OK [0.180 secs, 276736 KB]
Test 7: TEST OK [0.187 secs, 275712 KB]

又尼玛被坑了, 之前那个解法有点坑爹,没办法我脑袋简单,没想到dp.

对于点(i,j),其实只要求以i,j为右下顶点的最大正方形.

假设最大正方形是5,那么最后2,3,4,5都加1.

这个过程中的状态转移公式 min(i-1,j-1; i-1,j; i,j-1)+1

如果前面3个正方形有一个为0,那么点i,j最大的就是0+1,也就是边长为1....

dp这玩意没办法,要一点想象力,没想到真没办法. 在最大的test case上效率是我的一倍,因为我回去标记数组,相当做了2次。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: