uvalive 4256(dp),uvalive4256dp

來源:互聯網
上載者:User

uvalive 4256(dp),uvalive4256dp

題意:有從1到n的數字組成一個無向連通圖,給出了連通情況,然後給出一個數字序列,問這個序列要求相鄰的點要麼相等要麼在圖中是直接連通的,問最少修改序列中的幾個點可以讓序列滿足要求。

題解:f[i][j]表示前i個數組組成的序列以數字j結尾的最少修改點,那麼f[i][j] = min{f[i][j],f[i - 1][k] + (d[i] != j)},此時j==k或g[j][k] == 1。最後f[len][k]所有數字過一遍選出最大值就可以了。

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;const int N = 205;const int INF = 0x3f3f3f3f;int n, m, g[N][N], d[N], f[N][N];int main() {int t;scanf("%d", &t);while (t--) {scanf("%d%d", &n, &m);memset(g, 0, sizeof(g));int a, b;for (int i = 0; i < m; i++) {scanf("%d%d", &a, &b);g[a][b] = g[b][a] = 1;}scanf("%d", &m);for (int i = 1; i <= m; i++)scanf("%d", &d[i]);memset(f, INF, sizeof(f));for (int i = 1; i <= n; i++)f[1][i] = (i != d[1]);for (int i = 2; i <= m; i++)for (int j = 1; j <= n; j++)for (int k = 1; k <= n; k++)if (j == k || g[j][k])f[i][j] = min(f[i][j], f[i - 1][k] + (j != d[i]));int res = INF;for (int i = 1; i <= n; i++)res = min(res, f[m][i]);printf("%d\n", res);}return 0;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.