跳到正文

题解

题解:P15255 [USACO26JAN2] Moo Hunt B

zhoujunchen约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年2月12日
收录
2026年5月28日
更新
2026年11月10日
篇幅
约 3 分钟
获赞
1
题目
P15255

版本

  1. v1当前

状压。显然不止黄。

64 pts

我们开一个三元的 map,存储每个元组并去重。

然后用一个 NN 位的二进制数表示格子状态。如果第 ii 位是 11 就表示第 ii 个格子是 MM。

复杂度 O(2NT)O(2^NT),其中 TT 是不同的三元组,常数也蛮大。

C++
#include<bits/stdc++.h>
using namespace std;
int n,k,ans,cnt;
map<tuple<int,int,int>,int> mp;
int main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>n>>k;
	for(int i=0,x,y,z;i<k;i++){
        cin>>x>>y>>z,x--,y--,z--;
        if(y>z)swap(y,z);//(1,2,3) 与 (1,3,2) 没区别
        mp[{x,y,z}]++;
    }
	for(int S=0;S<(1<<n);S++){
		int sum=0;
		for(auto [i,r]:mp){
			int x=get<0>(i),y=get<1>(i),z=get<2>(i);
			if((S>>x&1)&&!(S>>y&1)&&!(S>>z&1))sum+=r;
		}
		if(sum>ans)ans=sum,cnt=1;
		else if(sum==ans)cnt++;
	}
	cout<<ans<<" "<<cnt;
	return 0;
}

100 pts

对上述算法优化。

定义一个变量 tottot 表示到目前为止不同元组的数量。

将 map 换成一个常规的三位数组,其存储的值为这个元组第一次出现时的 tottot 值。

cntpcnt_p 表示元组 pp 出现的个数。

C++
#include<bits/stdc++.h>
using namespace std;
int n,k,ans,cnt[8005],mp[25][25][25],tot,res;
struct node{
	int x,y,z;
}a[8005];
int main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>n>>k;
	memset(mp,-1,sizeof mp);
	for(register int i=1,x,y,z;i<=k;i++){
		cin>>x>>y>>z;x--,y--,z--;
		if(y>z)swap(y,z);
		if(mp[x][y][z]==-1){
			mp[x][y][z]=tot,
			a[tot]={x,y,z},
			cnt[tot++]=1;
		}else cnt[mp[x][y][z]]++;
	}
	for(register int S=0;S<(1<<n);S++){
		int sum=0;
		for(int i=0;i<tot;i++){
			int x=a[i].x,y=a[i].y,z=a[i].z;
			if((S>>x&1)&&!(S>>y&1)&&!(S>>z&1))sum+=cnt[i];
		}
		if(sum>ans)ans=sum,res=1;
		else if(sum==ans)res++;
	}
	cout<<ans<<" "<<res;
	return 0;
}

这暴力做法我也不知道为什么过了。复杂度好像还是一样的。

原文
存档评论2 条抓取于