平面上加入折線,每條折線由 X 段組成,第 i 段屬於類型 Y(方向)。求加入後平面被劃分的區域數模 MOD。多組操作,答案模 MOD 輸出。
每次加入一條折線(X 段,類型 Y):
Δ = X + Y * ( (2*curLines + (X-1)*Y) * X / 2 )。公式含除以 2,模 MOD 可能無逆元。但分子保證為偶數,用 Java BigInteger 精確計算後再取模。
BigInteger x1 = BigInteger.ONE, x2 = BigInteger.valueOf(2);
while (T--) {
int n = in.nextInt(); long mod = in.nextLong();
long curLines = 0, ans = 1 % mod;
while (n--) {
long X = in.nextLong(), Y = in.nextLong(); Y++;
BigInteger now = BigInteger.valueOf(2*curLines + (X-1)*Y);
now = now.multiply(BigInteger.valueOf(X)).divide(x2);
now = now.mod(BigInteger.valueOf(mod));
long tmp = now.longValue();
tmp = (tmp * Y + X) % mod;
ans = (ans + tmp) % mod;
curLines = (curLines + X * Y) % mod;
}
System.out.println(ans);
}
平面劃分區域數經典問題:每條新直線增加 (現有直線數+1) 區域。折線視為多段直線,利用等差數列求和推導 O(1) 增量公式。大數除法用 BigInteger 避免模逆元問題。數學推導是核心,代碼極簡。