Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя marcos07

Автор marcos07, 15 месяцев назад, По-английски

While solving the problem 1316E - Team Building.

When using

 long long dp[n][1<<p] ;
 memset(dp, -0x3f, sizeof dp) ;

giving the right answer.

But for

 long long dp[n][1<<p] ;
 memset(dp, 0, sizeof dp) ;

and

 vector<vector<long long>>dp(n,vector<long long>(1<<p,0)) ;

giving the wrong answer.

This is my complete code

void solve()
{
	int n , p , k ;
	vector<pair<int,int>> arr ;
	vector<vector<int>> mat ;
	cin >> n >> p >> k ;
	for(int i=0 ; i<n ; i++){
		int a ; cin >> a ;
		arr.push_back({a,i}) ;
	}
	mat=vector<vector<int>>(n,vector<int>(p)) ;
	for(int i=0 ; i<n ; i++){
		for(int j=0 ; j<p ; j++) cin >> mat[i][j] ;
	}
	sort(arr.rbegin(), arr.rend());
	long long dp[n][1<<p] ;
	
	memset(dp, -0x3f, sizeof dp) ;
	
	dp[0][0]=arr[0].ff ;
	for(int i=0 ; i<p ; i++){
		 dp[0][1<<i]=mat[arr[0].ss][i] ;
	}
	for(int i=1 ; i<n ; i++){
		for(int mask=0 ; mask<(1<<p) ; mask++){
			for(int j=0 ; j<p ; j++){
				if((mask&(1<<j))){
					dp[i][mask]=max(dp[i][mask],(dp[i-1][mask^(1<<j)]+mat[arr[i].ss][j])) ;
				}
			}
			dp[i][mask]=max(dp[i][mask],dp[i-1][mask]) ;
			if(i-__builtin_popcount(mask)<k)dp[i][mask]=max(dp[i][mask],dp[i-1][mask]+arr[i].ff) ;
		}
	}
	cout << dp[n-1][(1 << p)-1];
}

Can anyone help me with this?

  • Проголосовать: нравится
  • +7
  • Проголосовать: не нравится

»
15 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

-0x3f is negative infinity. When you fill the array with 0s, you might add states that are impossible to reach before.

  • »
    »
    15 месяцев назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Can you please explain this more, I am not able to understand why this will change the answer as the constraint is from 1 to 1e9.

    thanks.

    • »
      »
      »
      15 месяцев назад, # ^ |
      Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

      This is a common mistake in dp, where 0 + (a previous answer) might be used to update your current dp state but that 0 is not supposed to be possible. If it is set to negative infinity, its effects will be neglected.