TopCoder SRM 176 Deranged

代码:

#include<iostream>

#include<cstring>

#include<cstdio>

#include<string>

#include<set>

#include<map>

#include<cmath>

#include<algorithm>

#include<vector>

#include<cmath>

#include<queue>

#include<stack>



//#define ull unsigned long long

#define ll long long



using namespace std;



const int INF=0x3f3f3f3f;



const int MOD=1000003;

const int N=15;

ll dp0[1<<N],dp1[1<<N];

ll factorial[N];

class Deranged

{

    public:

    long long numDerangements(vector <int> nums)

    {

        int n=nums.size();

        memset(dp0,0,sizeof(dp0));

        dp0[(1<<n)-1]=1;

        for(int w=0;w<n;++w)

        {

            memset(dp1,0,sizeof(dp1));

            for(int i=0;i<(1<<n);++i)

            {

                for(int j=0;j<n;++j)

                if((i&(1<<j))&&nums[j]!=nums[w])

                {

                    dp1[i^(1<<j)]+=dp0[i];

                }

            }

            memcpy(dp0,dp1,sizeof(dp0));

        }

        ll sum=dp0[0];

        factorial[0]=1;

        for(int i=1;i<=n;++i)

        factorial[i]=factorial[i-1]*i;

        for(int i=0;i<n;++i)

        {

            int x=0;

            for(int j=0;j<n;++j)

            {

                if(nums[j]==i)

                ++x;

            }

            sum/=factorial[x];

        }

        return sum;

    }

};

  

你可能感兴趣的:(topcoder)