您的位置:首页 > 运维架构

Topcoder SRM 656 DIV2 1000 题解(动态规划)

2015-04-20 16:53 771 查看
题意:在1,2,3.....N这n个数的所有排列中,要求某些位置的数必需小于后一个数,而其余位置的数必选大于后一个数。给一个数组p,里面为哪些位置的数必需小于后一个数。求所有排列中满足条件的个数,答案模1000000007。

题解:dp[i][j] 表示前i个数,用1到i的排列来填,最后一个数填j的方案数。转移就是:

如果当前位要比前一个数大:

dp[i][j]+=dp[i-1][k],(k<j)

如果当前位要比前一个数小:

dp[i][j]+=dp[i-1][k],(k>=j)

dp[1][1]为1;

代码如下:

#line 4 "PermutationCountsDiv2.cpp"
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <sstream>
#define OUT(x) cout << #x << ": " << (x) << endl
#define SZ(x) ((int)x.size())
#define FOR(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long LL;
bool use[210];
long long dp[210][210];
const int mod=1000000007;
class PermutationCountsDiv2
{
public:
int countPermutations(int N, vector <int> pos)
{
int i,j,k;
int lp=pos.size();
memset(use,false,sizeof(use));
memset(dp,0,sizeof(dp));
for(i=0;i<lp;i++)
use[pos[i]+1]=true;
dp[1][1]=1;
for(i=2;i<=N;i++)
{
if(use[i])
{
for(j=1;j<=i;j++)
{
for(k=1;k<j;k++)
{
dp[i][j]=(dp[i][j]+dp[i-1][k])%mod;
}
}
}
else
{
for(j=1;j<=i;j++)
{
for(k=j;k<i;k++)
{
dp[i][j]=(dp[i][j]+dp[i-1][k])%mod;
}
}
}
}
int re=0;
for(i=1;i<=N;i++)
re=(re+dp
[i])%mod;
return re;
}

};

// Powered by FileEdit
// Powered by TZTester 1.01 [25-Feb-2003]
// Powered by CodeProcessor
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: