1. 程式人生 > >【uoj#209】[UER #6]票數統計 組合數+亂搞

【uoj#209】[UER #6]票數統計 組合數+亂搞

前綴 namespace color 合數 使用 預處理 枚舉 tdi !=

題目描述

一個長度為 $n$ 的序列,每個位置為 $0$ 或 $1$ 兩種。現在給出 $m$ 個限制條件,第 $i$ 個限制條件給出 $x_i$ 、$y_i$ ,要求至少滿足以下兩個條件之一:

  • 序列的前 $x_i$ 個位置中,恰好有 $y_i$ 個 $1$ ;
  • 序列的後 $y_i$ 個位置中,恰好有 $x_i$ 個 $1$ ;

求有多少個序列滿足所有限制條件。答案可能很大,只需要輸出它對 $998244353$ 取模後的結果即可。


題解

組合數+亂搞

顯然當 $x>y$ 時條件為前綴限制,$x<y$ 時條件為後綴限制。

既有前綴限制,又有後綴限制的情況下,我們枚舉總共1的個數,把後綴限制轉化為前綴限制。

如果所有限制均有 $x\ne y$ 則可以直接使用組合數計算。預處理組合數,單次計算的時間復雜度是 $O(n)$ 的。

當有 $x=y$ 時,顯然只需要考慮所有 $x=y$ 限制中 $x$ 最大的限制即可,總方案數為 滿足前綴+滿足後綴-滿足前綴和後綴。

時間復雜度 $O(n^2)$ 。

#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 1010
#define M 5010
#define mod 998244353
using namespace std;
int n , ax[N] , ay[N] , at , bx[N] , by[N] , bt , c[M][M] , v[M];
int solve(int x)
{
	int i , last = 0 , ans = 1;
	memset(v , -1 , sizeof(v));
	v[0] = 0 , v[n] = x;
	for(i = 1 ; i <= at ; i ++ )
	{
		if(v[ax[i]] != -1 && v[ax[i]] != ay[i]) return 0;
		v[ax[i]] = ay[i];
	}
	for(i = 1 ; i <= bt ; i ++ )
	{
		if(v[n - bx[i]] != -1 && v[n - bx[i]] != x - by[i]) return 0;
		v[n - bx[i]] = x - by[i];
	}
	for(i = 1 ; i <= n ; i ++ )
	{
		if(v[i] != -1)
		{
			if(v[i] < v[last]) return 0;
			ans = 1ll * ans * c[i - last][v[i] - v[last]] % mod , last = i;
		}
	}
	return ans;
}
int main()
{
	int T;
	scanf("%d" , &T);
	while(T -- )
	{
		at = bt = 0;
		int m , i , j , x , y , p = 0 , mx = 0 , ans = 0;
		scanf("%d%d" , &n , &m);
		for(i = 1 ; i <= m ; i ++ )
		{
			scanf("%d%d" , &x , &y) , mx = max(mx , min(x , y));
			if(x > y) ax[++at] = x , ay[at] = y;
			else if(x < y) bx[++bt] = y , by[bt] = x;
			else p = max(p , x);
		}
		c[0][0] = 1;
		for(i = 1 ; i <= n ; i ++ )
		{
			c[i][0] = 1;
			for(j = 1 ; j <= i ; j ++ )
				c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod;
		}
		for(i = mx ; i <= n ; i ++ )
		{
			at ++ , ax[at] = ay[at] = p , ans = (ans + solve(i)) % mod;
			bt ++ , bx[bt] = by[bt] = p , ans = (ans - solve(i) + mod) % mod;
			at -- , ans = (ans + solve(i)) % mod , bt -- ;
		}
		printf("%d\n" , ans);
	}
	return 0;
}

【uoj#209】[UER #6]票數統計 組合數+亂搞