typedeflonglong ll; constint maxn=2e5+10; int sum[maxn],cnt=maxn-1;
voidadd( int x ){ for(int i = x; i <= n; i += lowbit(i)) sum[i] += 1; } intquery( int x ){ int ans = 0; for(int i = x; i; i -= lowbit(i)) ans += sum[i]; return ans; }
intmain() { int n; cin>>n; ll ans=0; for( int i=1;i<=n;i++ ) { int x;cin>>x;x=1e5+10-x; ans+=query(x-1); add(x); } cout<<ans<<endl; }
voidadd(int x, int v) { for (int i = x; i <= n; i += lowbit(i)) tr[i] += v; }
intquery(int x) { int res = 0; for (int i = x; i; i -= lowbit(i)) res += tr[i]; return res; }
intmain() { cin >> n;
int sum = 0; for (int i = 0; i < n; i ++ ) { int x; cin >> x; sum += query(n) - query(x); add(x, 1); }
return0; }
错数排列
错排数递推公式及其证明 求n个数的错排数:D P [ n ] = ( n − 1 ) ∗ ( D P [ n − 1 ] + D P [ n − 2 ] ) 证明如下: ①考虑第n个元素,把它放在某一个位置,比如位置k,一共有n-1种放法 ②考虑第k个元素,这时有两种情况: (1)把它放到位置n,那么对于除n以外的n-1个元素,由于第k个元素放到了位置n,所以剩下n-2个元素的错排即可,有f ( n − 2 ) 种放法; (2)第k个元素不放到位置n,这时对于这n-1个元素的错排,有f ( n − 1 ) 种放法。
bool g[N][N]; int n; int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
intget(int x, int y){ int res = 0; for(int i = 0; i < 4; i ++) { int a = x + dx[i], b = y + dy[i]; if(g[a][b]) res ++; } return res; }
intmain(){ cin >> n; int res = 0; int a, b; for(int i = 0; i < n; i ++) { scanf("%d%d", &a, &b); a ++, b ++; g[a][b] = true; if(get(a, b) == 3) res ++; for(int i = 0; i < 4; i ++) { int x = a + dx[i], y = b + dy[i]; if(g[x][y]) { if(get(x, y) == 3) res ++; elseif(get(x, y) == 4) res --; } } printf("%d\n", res); } return0; }