解题代码:
package acm1009;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static int mWidth, mHight;
static int[][] pairs = new int[1009][2];
static HashMap<Integer, Integer> outMap = new HashMap<Integer, Integer>();
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
while ((mWidth = stdin.nextInt()) != 0) {
int num = 0;
int totleLen = 0;
outMap.clear();
while (!(((pairs[num][0] = stdin.nextInt()) == 0)&((pairs[num][1] = stdin.nextInt()) == 0))) {
totleLen += pairs[num++][1];
}
mHight = totleLen/mWidth;
findEdges(num);
outputImage(totleLen);
}
System.out.println("0");
}
private static void outputImage(int totleLen) {
System.out.println(mWidth);
Object[] keySet = outMap.keySet().toArray();
Arrays.sort(keySet);
int tempKey = Integer.parseInt(keySet[0].toString());
int temp = outMap.get(tempKey);
for (Object k : keySet) {
int key = Integer.parseInt(k.toString());
if (outMap.get(key) == temp) {
continue;
}
System.out.println(temp + " " + (key -tempKey));
temp = outMap.get(key);
tempKey = key;
}
System.out.println(temp + " " + (totleLen -tempKey));
System.out.println("0 0");
}
private static void findEdges(int num) {
int pos = 0;
int x,y;
for (int p = 0; p <= num; p++) {
x = pos/mWidth;
y = pos%mWidth;
for (int i = x-1; i <= x+1; i++) {
if (i < 0|| i >= mHight) {
continue;
}
for (int j = y-1; j <=y+1; j++) {
if (j < 0||j >= mWidth) {
continue;
}
int currPos = i*mWidth + j;
outMap.put(currPos, getMaxValue(currPos));
}
}
pos += pairs[p][1];
}
}
private static Integer getMaxValue(int currPos) {
int num=getnum(currPos),ret=0;
int row=currPos/mWidth;
int col=currPos%mWidth;
for (int i=row-1;i<=row+1;i++) {
if (i < 0|| i >= mHight) {
continue;
}
for (int j=col-1;j<=col+1;j++)
{
int tpos= i*mWidth+j;
if (j<0||j>=mWidth|| tpos==currPos)
continue;
int tmp=getnum(tpos);
if (Math.abs(tmp-num)>ret)ret=Math.abs(tmp-num);
}
}
return ret;
}
private static int getnum(int currPos) {
int p=0,i=0;
while (p<=currPos)
p+=pairs[i++][1];
return pairs[i-1][0];
}
}
注意* 跳跃式计算,第一个点和最后一个点要单算,不然会WA!