Algorithm
Problem Statement for Deranged
problem link- https://community.topcoder.com/stat?c=problem_statement&pm=2013 |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <vector>
#include <algorithm>
#include <memory.h>
using namespace std;
class Deranged {
public:
static long long dp[(1 << 16)][16];
long long numDerangements(vector <int> nums) {
sort(nums.begin(), nums.end());
memset(dp, -1, sizeof dp);
long long ret = rec(0, 0, nums);
int fr[16] = {0};
for(int i = 0; i < nums.size(); ++i)
++fr[nums[i]];
for(int i = 0; i < 16; ++i)
ret /= fact(fr[i]);
return ret;
}
long long rec(int idx, int msk, vector<int>&nums) {
if(__builtin_popcount(msk) == int(nums.size()))
return 1;
long long &ret = dp[msk][idx];
if(ret != -1)
return ret;
ret = 0;
for(int i = 0; i < nums.size(); ++i)
if(((msk >> i) & 1) == 0 && nums[idx] != nums[i])
ret += rec(idx + 1, msk | (1 << i), nums);
return ret;
}
long long fact(int x) {
long long f = 1;
for(int i = 2; i <= x; ++i)
f *= i;
return f;
}
};
long long Deranged::dp[][16] = {0};
Copy The Code &
Try With Live Editor
Input
{1,1,2,2,3}
Output
4
Demonstration
TopCoder Solution SRM176-D1-500 Problem Statement for Deranged C,C++, Java, Js and Python ,SRM176-D1-500