結果

問題 No.3276 Make Smaller Popcount
ユーザー snrnsidy
提出日時 2025-09-19 21:43:53
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 1,557 ms / 2,000 ms
コード長 2,035 bytes
コンパイル時間 1,912 ms
コンパイル使用メモリ 198,964 KB
実行使用メモリ 7,720 KB
最終ジャッジ日時 2025-09-19 21:44:38
合計ジャッジ時間 44,803 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 28
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

long long int dp[33][33][2];

long long int solve(string s,int cnt)
{
    for(int i=0;i<=32;i++)
    {
        for(int a=0;a<=32;a++)
        {
            for(int j=0;j<2;j++)
            {
                dp[i][a][j] = 1e18;
            }
        }
    }

    dp[0][0][0] = 0;

    for(int i=0;i<32;i++)
    {
        for(int j=0;j<=i;j++)
        {
            for(int k=0;k<2;k++)
            {
                if(dp[i][j][k] >= 1e18) continue;
                int x = s[i] - '0';
                x += k;
                int c = x/2;
                if(x%2==0)
                {
                    dp[i+1][j][c] = min(dp[i+1][j][c],dp[i][j][k]);
                }
                else
                {
                    if(j+1 <= 32) dp[i+1][j+1][c] = min(dp[i+1][j+1][c],dp[i][j][k]);
                }

                x += 1;
                c = x/2;
                if(x%2==0)
                {
                    dp[i+1][j][c] = min(dp[i+1][j][c],dp[i][j][k] + (1LL << i));
                }
                else
                {
                    if(j+1 <= 32) dp[i+1][j+1][c] = min(dp[i+1][j+1][c],dp[i][j][k] + (1LL << i));
                }                
            }
        }
    }

    long long int res = 1e18;
    for(int i=0;i<cnt;i++)
    {
        res = min(res,dp[32][i][0]);
        res = min(res,dp[32][i][1]);
    }

    return res;
}
int main(void)
{
	cin.tie(0);
	ios::sync_with_stdio(false);

    int tc;
    cin >> tc;

    while(tc--)
    {
        long long int n;
        cin >> n;

        int cnt = 0;
        string s = "";
        for(int x=0;x<32;x++)
        {
            int b = (n%2);
            cnt += b;
            s = s + (char)(b + '0');
            n/=2;
        }

        if(cnt==1)
        {
            cout << -1 << '\n';
        }
        else
        {
            long long int value = solve(s,cnt);

            if(value >= 1e18) cout << -1 << '\n';
            else cout << value << '\n';
        }

    }
	return 0;
}
0