Topcoder SRM 452 div 2 level 3 HamiltonPath
2014-11-03 16:42
411 查看
给你一张完全图,指定一些边必须要走,问你走出一条哈密顿路有多少种走法。说是路径,其实就是个排列。指定一些元素连在一起,有多少种排法。先判断他给的关系是不是线性的。如果是树性的或是有环直接返0。长大于2的线正过来反过去有2中排法,再乘以线段总数的阶乘就可以了。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstdlib>
#include <string>
#include <vector>
#define maxn 64
using namespace std;
const int MOD=1e9+7;
int p[maxn],cnt[maxn];
int du[maxn];
int findset(int x)
{
return x==p[x]?x:p[x]=findset(p[x]);
}
bool unionset(int x,int y)
{
int fx=findset(x);
int fy=findset(y);
if(fx==fy)
return 0;
p[fx]=fy;
cnt[fy]+=cnt[fx];
return 1;
}
class HamiltonPath
{
public: int countPaths(vector <string> s)
{
int n=s.size();
for(int i=0;i<n;i++)
cnt[i]=1,p[i]=i;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(s[i][j]=='Y')
{
if(!unionset(i,j))
return 0;
du[i]++;du[j]++;
}
}
}
for(int i=0;i<n;i++)
if(du[i]>2)
return 0;
long long ans=1,num=0;
for(int i=0;i<n;i++)
{
if(i==p[i])
{
if(cnt[i]>1)
ans=ans*2%MOD;
num++;
}
}
for(int i=1;i<=num;i++)
ans=ans*i%MOD;
return ans;
}
};
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstdlib>
#include <string>
#include <vector>
#define maxn 64
using namespace std;
const int MOD=1e9+7;
int p[maxn],cnt[maxn];
int du[maxn];
int findset(int x)
{
return x==p[x]?x:p[x]=findset(p[x]);
}
bool unionset(int x,int y)
{
int fx=findset(x);
int fy=findset(y);
if(fx==fy)
return 0;
p[fx]=fy;
cnt[fy]+=cnt[fx];
return 1;
}
class HamiltonPath
{
public: int countPaths(vector <string> s)
{
int n=s.size();
for(int i=0;i<n;i++)
cnt[i]=1,p[i]=i;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(s[i][j]=='Y')
{
if(!unionset(i,j))
return 0;
du[i]++;du[j]++;
}
}
}
for(int i=0;i<n;i++)
if(du[i]>2)
return 0;
long long ans=1,num=0;
for(int i=0;i<n;i++)
{
if(i==p[i])
{
if(cnt[i]>1)
ans=ans*2%MOD;
num++;
}
}
for(int i=1;i<=num;i++)
ans=ans*i%MOD;
return ans;
}
};
相关文章推荐
- TopCoder SRM 558 DIV2 Level 3:CatAndRabbit
- SRM 483 Div II Level Two: MovieSeating, TopCoder上正确率不到%10的题
- Topcoder SRM 547 DIV1 Level 1: Pillars
- topcoder srm 451 div2 level 3 PizzaDelivery
- SRM 578 Div II Level Three: WolfInZooDivTwo,Dynamic Programming,求教!
- topcoder srm 510 div1
- Topcoder SRM144 div2 1100
- TopCoder SRM 664 Div2 Level One
- topcoder SRM 617 DIV2 SlimeXSlimonadeTycoon
- topcoder SRM 624 DIV2 CostOfDancing
- TopCoder SRM 644 Div2 Problem 500 - LostCharacter (贪心)
- topcoder srm 515 div1
- 【汇总】贴一下TopCoder SRM 303 DIV I 500分题的题目和...
- [topcoder]SRM 646 DIV 2
- TopCoder - SRM521 div1 500 RangeSquaredSubsets
- TopCoder SRM 597 Div1 第3题
- topcoder-srm-233-div2
- Topcoder SRM 662 DIV1
- TopCoder SRM 653 Div2 Problem 500 - RockPaperScissorsMagicEasy (DP)
- topcoder srm 370 div1