No.134 走れ!サブロー君

No.134 走れ!サブロー君 - yukicoder

  • bit DP の問題。最初 weigth の値も込みの dp[bit][weight] みたいな DP かと思ったが bit だけで weight が計算できることに気づけた。
  • 問題文の重みが double だってことに気づかずに int w; に cin>>w; してしまって WA してしまった。
  • bit DP はまだまだ実装練習が必要そう。
class GoSabrou {
public:
    void solve(void) {
            // 巡回セールスマン問題の応用
            int x0,y0;
            cin>>x0>>y0;

            int N;
            cin>>N;

            // 配達先
            vector<tuple<int,int,double>> dest;

            // 出発地も登録しておく
            dest.emplace_back(x0,y0,0);
            REP(i,N)
            {
                int x,y;
                double w;
                cin>>x>>y>>w;
                dest.emplace_back(x,y,w);
            }
            ++N; // 出発点分加算

            // 距離を事前計算しておく
            const int inf = (1<<30);
            vector<vector<int>> dist(N,vector<int>(N,inf));
            REP(i,N)
            FOR(j,i+1,N)
            {
                const auto &p = dest[i];
                const auto &q = dest[j];

                // 距離はマンハッタン距離
                int d = abs(get<0>(p)-get<0>(q)) + abs(get<1>(p)-get<1>(q));
                dist[i][j] = dist[j][i] = d;
            }

            // 総荷重量を計算しておく
            // weights[unvis] := 未配達先が unvis であるときの総重量
            vector<double> weights(1<<N, 0);
            REP(unvis, (1<<N))
            {
                double w = 0;
                REP(i,N) if ( unvis & (1<<i) )
                    w += get<2>(dest[i]);
                weights[unvis] = w;
            }

            // dp[unvis][i] := 未配達先が unvis で現在地が v のときの配達終了までの最短時間
            vector<vector<double>> dp(1<<N, vector<double>(N,inf));

            // O((1<<N)*N^2)
            // 頂点 0 からスタートして全部巡回させる
            dp[(1<<N)-1][0] = 0;

            // 0 頂点を除いた全ビットからスタート
            for (int unvis = (1<<N)-2; unvis >= 0; --unvis)
            {
                // 次の移動先 v 毎
                REP(v,N)
                {
                    // 移動前 u 毎
                    REP(u,N)
                    {
                        // 移動前が未到達なら飛ばす
                        if ( unvis & (1<<u) )
                            continue;
                        double cost = (weights[unvis]+100.0)/120.0 * dist[u][v] + get<2>(dest[v]);
                        dp[unvis][v] = min(dp[unvis][v], dp[unvis|(1<<u)][u] + cost);
                    }
                }
            }
            // 一周してもどってきた
            cout<<setprecision(20)<<dp[0][0]<<endl;
    }
};