• AtCoder AGC043D Merge Triplets (DP、组合计数)


    题目链接

    https://atcoder.jp/contests/agc043/tasks/agc043_d

    题解

    考场上想到正确做法,然后思考实现细节的时候做法逐渐扭曲,最后GG……考后睡了一觉冷静了一下才改对,我是屑……
    考虑序列归并的过程,可以发现每次会将某序列的相邻两个前缀最大值之间的部分依次加入。然后不难发现,最终产生的序列实际上和前缀最大值有某种神秘的关系。具体来讲,我们把每个前缀最大值开头到下一个之前的这部分单独看成一个组,而抛弃原来“划分成的 (n) 个小序列”的概念,组和组不同当且仅当组中至少一个元素不同,那么计数答案就相当于计数这样划分组的方案,满足所有组恰好能够拼成 (n) 个长度为 (3) 的序列,组之间无编号。
    于是可以转化成将 ([1,3n]) 这些数分成若干组,每组大小不超过 (3),组之间无编号,且大小为 (1) 的组数减去大小为 (2) 的组数大于等于 (0) 且为 (3) 的倍数。然后直接DP即可。
    时间复杂度 (O(n^2)).

    代码

    #include<bits/stdc++.h>
    #define llong long long
    #define mkpr make_pair
    #define riterator reverse_iterator
    using namespace std;
    
    inline int read()
    {
    	int x = 0,f = 1; char ch = getchar();
    	for(;!isdigit(ch);ch=getchar()) {if(ch=='-') f = -1;}
    	for(; isdigit(ch);ch=getchar()) {x = x*10+ch-48;}
    	return x*f;
    }
    
    const int mxN = 2000;
    llong P;
    llong f[mxN*3+3][mxN*4+3];
    int n;
    
    void updsum(llong &x,llong y) {x = x+y>=P?x+y-P:x+y;}
    
    int main()
    {
    	scanf("%d%lld",&n,&P);
    	f[0][n+1] = 1ll;
    	for(int i=0; i<=3*n; i++)
    	{
    		for(int j=-n; j<=3*n; j++)
    		{
    			updsum(f[i+1][j+1+(n+1)],f[i][j+(n+1)]);
    			updsum(f[i+2][j-1+(n+1)],f[i][j+(n+1)]*(i+1ll)%P);
    			updsum(f[i+3][j+(n+1)],f[i][j+(n+1)]*(i+2ll)%P*(i+1ll)%P);
    		}
    	}
    	llong ans = 0ll;
    	for(int i=0; i<=n; i++)
    	{
    		updsum(ans,f[3*n][3*i+(n+1)]%P);
    	}
    	printf("%lld
    ",ans);
    	return 0;
    }
    
  • 相关阅读:
    LeetCode-860. Lemonade Change
    LeetCode-455.Assign Cookies
    LeetCode-122.Best Time to Buy and Sell Stock II
    LeetCode-438.Find All Anagrams in a String
    LeetCode-50.Pow(x,n)
    LeetCode-236.Lowest Common Ancestor of a Binary Tree
    LeetCode-235.Lowest Common Ancestor of a Binary Search Tree
    LeetCode-98.Validate Binary Search Tree
    LeetCode-18.4Sum
    LeetCode-15.3Sum
  • 原文地址:https://www.cnblogs.com/suncongbo/p/12546785.html
Copyright © 2020-2023  润新知