ACM模板库

ACM模板库


斯坦纳树

<pre><code class="language-cpp">#include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &lt;queue&gt; using namespace std; typedef pair&lt;int, int&gt; P; const int maxn = 110; vector&lt;P&gt; mp[maxn]; priority_queue&lt;P, vector&lt;P&gt;, greater&lt;P&gt; &gt; que; int id[maxn]; bool vis[maxn]; int dp[maxn][1 &lt;&lt; 10]; int n, m, k, x, y; void dijkstra(int s){ memset(vis, false, sizeof(vis)); while(!que.empty()){ int u = que.top().second; que.pop(); if(vis[u]) continue; vis[u] = true; for(int i = 0; i &lt; mp[u].size(); i++){ int to = mp[u][i].second; int w = mp[u][i].first; if(dp[to][s] &gt; dp[u][s] + w){ dp[to][s] = dp[u][s] + w; que.push(P(dp[to][s], to)); } } } } int main(){ scanf("%d%d%d%d%d", &amp;n, &amp;m, &amp;k, &amp;x, &amp;y); id[x] = k + 1, id[y] = k + 2, k += 2; int num = k; for(int i = 1; i &lt;= n; i++){ int t; scanf("%d", &amp;t); if (i == x || i == y) continue; if(t == 0) id[i] = ++num; else id[i] = t; } n = num; for(int i = 1; i &lt;= m; i++){ int u, v, w; scanf("%d%d%d", &amp;u, &amp;v, &amp;w); if(id[u] == id[v]) continue; mp[id[u]].push_back(P(w, id[v])); mp[id[v]].push_back(P(w, id[u])); } memset(dp, 0x3f, sizeof(dp)); for(int i = 1; i &lt;= k; i++) dp[i][1 &lt;&lt; (i - 1)] = 0; for(int s = 1; s &lt; (1 &lt;&lt; k); s++){ for(int i = 1; i &lt;= n; i++){ for(int subs = s &amp; (s - 1); subs; subs = s &amp; (subs - 1)){ dp[i][s] = min(dp[i][s], dp[i][subs] + dp[i][s ^ subs]); } if(dp[i][s] != 0x3f3f3f3f) que.push(P(dp[i][s], i)); } dijkstra(s); } printf("%d", dp[1][(1 &lt;&lt; k) - 1]); return 0; }</code></pre>

页面列表

ITEM_HTML