D - Island Tour
题目大意
思路解析:
可以发现 1->2->4 整体减1变为5->1->3,
其中2->4的距离等于1->3的距离
其中1->2的距离不等于5->1的距离,则只有当[xj - i] <= 0后的xj - > xj+1 和 xj -> xj-1的距离才会发生改变。所有我们枚举当前需要整体减去i,然后看哪些点会小于等于0,又因为我们可以每次记录上一次i-1的答案,所以我们只需要统计哪些点减i会等于0引起的距离变化。
如果我们通过记录哪些点等于i,可以减少统计答案时,遍历哪些点等于i的过程。
代码实现:
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
int n = input.nextInt();
int m = input.nextInt();
Vector<Integer>[] arr = new Vector[200001];
for (int i = 0; i < 200001; i++) {
arr[i] = new Vector<Integer>();
}
int[] x = new int[m];
long ans = 0;
for (int i = 0; i < m; i++) {
x[i] = input.nextInt();
if (i != 0)
ans += Math.abs(x[i] - x[i - 1]);
arr[x[i]].add(i);
}
long res = ans;
for (int i = 1; i <= n - 1; i++) {
for (int t = 0; t < arr[i].size(); t++) {
int j = arr[i].get(t);
if (j >= 1){
int k = (x[j - 1] - i + n) % n;
ans += Math.abs(n - k) - k;
}
if (j < m - 1){
int k = (x[j + 1] - i + n) % n;
ans += Math.abs(n - k) - k;
}
}
res = Math.min(ans, res);
}
out.println(res);
out.flush();
out.close();
br.close();
}
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static Input input = new Input(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static class Input {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Input(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
}