• 宝藏


    好累啊,不想写题目大意了,放个链接吧。
    算法:类似于最小生成树的DP写法(其实一毛一样),预处理转移后直接转移
    代码:

    #include<bits/stdc++.h>
    #define INF 100000000
    #define maxn 12
    using namespace std;
    
    int n,m,mat[maxn+5][maxn+5];
    int w[maxn+5][1<<maxn];
    int dp[maxn+5][1<<maxn];
    int tot,change[600007][3];
    int res=INF;
    
    void dfs(int from,int to,int pos){
    	if (pos>n){
    		change[++tot][0]=from;
    		change[tot][1]=to;
    		return;
    	}
    	dfs(from+(1<<pos-1),to+(1<<pos-1),pos+1);
    	dfs(from,to,pos+1);
    	dfs(from,to+(1<<pos-1),pos+1);
    }
    
    int bitget(int x,int pos){
    	return (x>>pos)&1; 
    }
    
    int main(){
    	scanf("%d%d", &n, &m);
    	for (int i=1; i<=n; i++)
    		for (int j=1; j<=n; j++)
    			mat[i][j]=INF;
    	while (m--){
    		int u,v,cost;
    		scanf("%d%d%d", &u, &v, &cost);
    		mat[u][v]=min(mat[u][v],cost);
    		mat[v][u]=mat[u][v];
    	}
    	for (int sta=0; sta<(1<<n); sta++)
    		for (int i=1; i<=n; i++){
    			w[i][sta]=INF;
    			for (int j=1; j<=n; j++)
    				if ((sta>>j-1)&1) w[i][sta]=min(w[i][sta],mat[i][j]);
    		}
    	dfs(0,0,1);
    	for (int k=1; k<=tot; k++)
    		for (int i=1; i<=n; i++)
    			if (bitget(change[k][0],i-1)==0 && bitget(change[k][1],i-1)==1) 
    				if (change[k][2]<INF) change[k][2]+=w[i][change[k][0]];
    	for (int i=0; i<=n; i++)
    		for (int sta=0; sta<(1<<n); sta++) dp[i][sta]=INF;
    	for (int sta=1; sta<(1<<n); sta<<=1) dp[0][sta]=0;
    	for (int i=1; i<=n; i++){
    		for (int k=1; k<=tot; k++)
    			dp[i][change[k][1]]=min(dp[i][change[k][1]],dp[i-1][change[k][0]]+change[k][2]*i);
    		res=min(res,dp[i][(1<<n)-1]);
    	}
    	printf("%d
    ",res);
    	return 0;
    } 
    
    来自YJZoier的博客 转载请注明出处
  • 相关阅读:
    register_shutdown_function
    字节转换
    考虑 PHP 5.0~5.6 各版本兼容性的 cURL 文件上传
    linux--svn checkout
    linux命令
    linux---mysql忘记密码
    array_merge函数的注意事项
    逻辑卷使用记录笔记
    系统设计时关于性能问题处理的几点心得
    SSH防暴力破解脚本
  • 原文地址:https://www.cnblogs.com/YJZoier/p/9312588.html
Copyright © 2020-2023  润新知