问题 G: Breed Assignment--------------思维(爆搜)

题目描述
Farmer John has N cows (2 <= N <= 15) that are each one of three different breeds: Holsteins, Jerseys, or Guernseys.

Unfortunately, FJ cannot remember the exact breeds of his cows! He does, however, remember a list of K (1 <= K <= 50) relationships between pairs of cows; for example, he might remember that cows 1 and 2 have the same breed,
or that cows 1 and 5 have different breeds.

Give FJ’s list of relationships between pairs of cows, please help him compute the number of different possible assignments of breeds to his cows (this number could be zero if his list contains contradictory information).
输入

  • Line 1: Two space-separated integers: N and K.
  • Lines 2…1+K: Each line describes the relationship between a pair of cows x and y (1 <= x,y <= N, x != y). It is either of the form “S x y”, meaning that x and y have the same breed, or “D x y”, meaning that x and y have different breeds.
    输出
  • Line 1: The number of possible breed assignments.
    样例输入 Copy
    4 2
    S 1 2
    D 1 3
    样例输出 Copy
    18
    提示
    There are 4 cows. Cows 1 and 2 have the same breed, and cows 1 and 3 have different breeds.The following six breed assignments are possible for the first 3 cows: HHG, HHJ, GGH, GGJ, JJH, JJG. For each of these, we can have 3 possible breed assignments for the 4th cow, giving a total of 18 different assignments consistent with FJ’s list.

解析:
我们用二维矩阵把关系的边存起来。
然后爆搜,去枚举状态

#pragma GCC optimize(3)
#include<bits/stdc++.h>
using namespace std;
int g[20][20];
int x,y;
int n,k;
int ans=0;
int a[100005];
char op;
void dfs(int now)
{
	if(now>n) 
	{
		ans++;
		return ;
	}
	for(int i=1;i<=3;i++)//枚举状态
	{
		int f=0;
		for(int j=1;j<now;j++) //判断当前位与之前是否有关系
		{
			if(i!=a[j]&&g[now][j]==1)//如果有连边但不是同一个状态 不符合的
			{
				f=1;
				break;
			}
			if(i==a[j]&&g[now][j]==-1)//如果是一个状态的,但是无法连边,也是不行的
			{
				f=1;
				break;
			}
		}
		if(!f)
		{
			a[now]=i;
			dfs(now+1);
			a[now]=0;
		}
	 } 
}
int main()
{
	scanf("%d %d",&n,&k);
	while(k--)
	{
		cin>>op>>x>>y;
		if(op=='S') g[x][y]=g[y][x]=1;
		else g[x][y]=g[y][x]=-1;
	}	
	dfs(1);
	cout<<ans<<endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值