UVALive4256 Salesmen

题意:一个n个点的联通图(n<=100)的无向联通图,还有一个长度为L序列(L<200),问最少改变序列中几个数使得序列相邻两个数是相同或者在图中相邻

题解:dp[i][j]代表第i个数变为j的最小次数,O(n*L*n)

#include 
#define maxn 210
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
int g[maxn][maxn], a[2*maxn], dp[maxn][maxn];
int main(){
    int n, m, t, b, ans, c, T;
    scanf("%d", &T);
    while(T--){
        ans = INF;
        memset(dp, INF, sizeof(dp));
        memset(g, 0, sizeof(g));
        scanf("%d%d", &n, &m);
        for(int i=0;i){
            scanf("%d%d", &b, &c);
            g[b][c] = g[c][b] = 1;
        }
        for(int i=1;i<=n;i++) g[i][i] = 1;
        scanf("%d", &t);
        for(int i=1;i<=t;i++)
            scanf("%d", &a[i]);
        for(int i=1;i<=n;i++) dp[1][i] = (i==a[1])?0:1;
        for(int i=2;i<=t;i++){
            for(int j=1;j<=n;j++){
                for(int k=1;k<=n;k++){
                    if(g[j][k] == 1){
                        dp[i][j] = min(dp[i][j], dp[i-1][k]+((j==a[i])?0:1));
                    }
                }
            }
        }
        for(int i=1;i<=n;i++)
            ans = min(ans, dp[t][i]);
        printf("%d\n", ans);
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/Noevon/p/7645631.html

你可能感兴趣的:(UVALive4256 Salesmen)