2019 10th Lanqiao Cup Provincial Competition C++ University Group A Group I Question Candy【Dp】

Portal: AcWing 1243. Candy

Ideas

State compression, compress the candy collection taken from each package into a binary number, set the iiThe binary number of package i isa [i] a[i]a[i]

d p [ i ] dp[i] d p [ i ] represents the composition stateiii The minimum number of packets required.

From state jjj Tori No.iiThe next stateto whichpacket i candies transferto = j ∣ a [i] to=j|a[i]to=j a [ i ] , there is a state transition equation: dp [to] = min (dp [to], dp [j] + 1) dp[to]=min(dp[to],dp[j]+1 )dp[to]=min(dp[to],dp[j]+1)

AC code

#include <bits/stdc++.h>
using namespace std;
const int N=105,M=(1<<20)+10;
int n,m,k,x,a[N],dp[M];
// dp[i]表示组成i状态的所需的最小包数
int main() 
{
    
    
	ios::sync_with_stdio(false);
	cin>>n>>m>>k; 
	memset(dp,-1,sizeof(dp));
	for(int i=1;i<=n;i++)
	{
    
    
		int s=0;
		for(int j=1;j<=k;j++)
		{
    
    
			cin>>x;
			s|=(1<<(x-1)); // x-1是为了让2的幂次从0开始
		}
		dp[s]=1;
		a[i]=s;
	}
	for(int i=1;i<=n;i++)
	{
    
    
		for(int j=0;j<(1<<m);j++) // 枚举m个糖果是否被取的所有状态
		{
    
    
			if(dp[j]==-1)continue;
			int to=j|a[i]; // 若取,则下一状态为to
			if(dp[to]!=-1) // 之前达到过dp[to]
			{
    
    
				dp[to]=min(dp[to],dp[j]+1);	
			}
			else 
			{
    
    
				dp[to]=dp[j]+1;
			}
		}
	}
	printf("%d\n",dp[(1<<m)-1]); // 糖果全取的状态为(1<<m)-1,即全为1的二进制数,长度为m
	return 0;
}
/*
6 5 3 
1 1 2 
1 2 3 
1 1 3 
2 3 5 
5 4 2 
5 1 2
ans:2
*/

Guess you like

Origin blog.csdn.net/ljw_study_in_CSDN/article/details/109121856