[LOJ6570] caterpillar count

Keywords: Programming less

[title link]

[main ideas]

  • The main chain of the caterpillar is defined as the part of the node with the degree of removal of 111.
  • If the length of the main chain is less than 222, it is a chrysanthemum diagram, obviously there are N − [N=2]N-[N=2]N − [N=2] kinds.
  • Consider enumerating the length of the main chain i (i ≥ 2)i\ (i\geq 2)i (i ≥ 2), arranging the points on the main chain arbitrarily, there are Ni2 \ frac {n ^ {i} {2} 2Ni.
  • For the remaining nodes, we require that the head and tail of the main chain must have nodes, and whether the remaining nodes have any children.
  • According to the inclusion exclusion principle, the number of hung sub nodes is iN − I − 2(i − 1)N − i+(i − 2)N − ii^{N-i}-2(i-1)^{N-i}+(i-2)^{N-i}iN − I − 2(i − 1)N − i+(i − 2)N − I.
  • Time complexity O(NLogN)O(NLogN)O(NLogN).
  • Using the method of generating function, all the answers of 1 ∼ N1\sim N1 ∼ n can be obtained.

[Code]

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
const int P = 998244353;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
template <typename T> void chkmax(T &x, T y) {x = max(x, y); }
template <typename T> void chkmin(T &x, T y) {x = min(x, y); } 
template <typename T> void read(T &x) {
	x = 0; int f = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
	for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
	x *= f;
}
template <typename T> void write(T x) {
	if (x < 0) x = -x, putchar('-');
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
}
template <typename T> void writeln(T x) {
	write(x);
	puts("");
}
int fac[MAXN], inv[MAXN];
int power(int x, int y) {
	if (y == 0) return 1;
	int tmp = power(x, y / 2);
	if (y % 2 == 0) return 1ll * tmp * tmp % P;
	else return 1ll * tmp * tmp % P * x % P;
}
int getc(int x, int y) {
	if (y > x) return 0;
	else return 1ll * fac[x] * inv[y] % P * inv[x - y] % P;
}
void init(int n) {
	fac[0] = 1;
	for (int i = 1; i <= n; i++)
		fac[i] = 1ll * fac[i - 1] * i % P;
	inv[n] = power(fac[n], P - 2);
	for (int i = n - 1; i >= 0; i--)
		inv[i] = inv[i + 1] * (i + 1ll) % P;
}
void update(int &x, int y) {
	x += y;
	if (x >= P) x -= P;
}
int main() {
	int n; read(n); init(n);
	int ans = n - (n == 2);
	for (int i = 2; i <= n - 2; i++) {
		int coef = 1ll * fac[n] * inv[n - i] % P * inv[2] % P;
		int now = power(i, n - i);
		update(now, P - 2ll * power(i - 1, n - i) % P);
		update(now, power(i - 2, n - i));
		update(ans, 1ll * now * coef % P);
	}
	writeln(ans);
	return 0;
}

Posted by anthonyw17 on Fri, 29 Nov 2019 10:03:51 -0800