2013
11-10

# SOLDIERS

N soldiers of the land Gridland are randomly scattered around the country.

A position in Gridland is given by a pair (x,y) of integer coordinates. Soldiers can move – in one move, one soldier can go one unit up, down, left or right (hence, he can change either his x or his y coordinate by 1 or -1).

The soldiers want to get into a horizontal line next to each other (so that their final positions are (x,y), (x+1,y), …, (x+N-1,y), for some x and y). Integers x and y, as well as the final order of soldiers along the horizontal line is arbitrary.

The goal is to minimise the total number of moves of all the soldiers that takes them into such configuration.

Two or more soldiers must never occupy the same position at the same time.

The first line of the input contains the integer N, 1 <= N <= 10000, the number of soldiers.

The following N lines of the input contain initial positions of the soldiers : for each i, 1 <= i <= N, the (i+1)st line of the input file contains a pair of integers x[i] and y[i] separated by a single blank character, representing the coordinates of the ith soldier, -10000 <= x[i],y[i] <= 10000.

The first and the only line of the output should contain the minimum total number of moves that takes the soldiers into a horizontal line next to each other.

5
1 2
2 2
1 3
3 -2
3 3


8

import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner;

public class Main {

static int x[];
static int y[];

public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
if (scan.hasNext()) {
int n = scan.nextInt();
x = new int[n];
y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = scan.nextInt();
y[i] = scan.nextInt();
}
Arrays.sort(x);
Arrays.sort(y);
for (int i = 0; i < n; i++) {
x[i] -= i;
}
Arrays.sort(x);
int midX = x[(n + 1) / 2 - 1];
int midY = y[(n + 1) / 2 - 1];
int num = 0;
for (int i = 0; i < n; i++) {
num += Math.abs(x[i] - midX) + Math.abs(y[i] - midY);
}
System.out.println(num);

}
}
}

1. 问题3是不是应该为1/4 .因为截取的三段，无论是否能组成三角形， x， y-x ，1-y,都应大于0，所以 x<y,基础应该是一个大三角形。小三角是大三角的 1/4.

2. 可以参考算法导论中的时间戳。就是结束访问时间，最后结束的顶点肯定是入度为0的顶点，因为DFS要回溯

3. #include <cstdio>
#include <cstring>

const int MAXSIZE=256;
//char store[MAXSIZE];
char str1[MAXSIZE];
/*
void init(char *store) {
int i;
store['A']=’V', store['B']=’W',store['C']=’X',store['D']=’Y',store['E']=’Z';
for(i=’F';i<=’Z';++i) store =i-5;
}
*/
int main() {
//freopen("input.txt","r",stdin);
//init(store);
char *p;
while(fgets(str1,MAXSIZE,stdin) && strcmp(str1,"STARTn")==0) {
if(p=fgets(str1,MAXSIZE,stdin)) {
for(;*p;++p) {
//*p=store[*p]
if(*p<’A’ || *p>’Z') continue;
if(*p>’E') *p=*p-5;
else *p=*p+21;
}
printf("%s",str1);
}
fgets(str1,MAXSIZE,stdin);
}
return 0;
}