洛谷 P1171 售货员的难题 【状压dp】

题目描述

某乡有n个村庄(1<n<20),有一个售货员,他要到各个村庄去售货,各村庄之间的路程s(0<s<1000)是已知的,且A村到B村与B村到A村的路大多不同。为了提高效率,他从商店出发到每个村庄一次,然后返回商店所在的村,假设商店所在的村庄为1,他不知道选择什么样的路线才能使所走的路程最短。请你帮他选择一条最短的路。

输入输出格式

输入格式:

村庄数n和各村之间的路程(均是整数)。

输出格式:

最短的路程。

输入输出样例

输入样例#1: 复制
3
0 2 1
1 0 2
2 1 0
输出样例#1: 复制
3

说明

输入解释

3 {村庄数}

0 2 1 {村庄1到各村的路程}

1 0 2 {村庄2到各村的路程}

2 1 0 {村庄3到各村的路程}



这道题卡常卡的太极限了= =

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define min(a,b) (a) < (b) ? (a):(b)
using namespace std;
const int maxn = 20,maxm = 1 << 20,INF = 1000000000;

inline int read(){
	int out = 0,flag = 1;char c = getchar();
	while (c < 48 || c > 57) {if (c == '-') flag = -1; c = getchar();}
	while (c >= 48 && c <= 57) {out = out * 10 + c - 48; c = getchar();}
	return out * flag;
}

int G[maxn][maxn],f[maxm][maxn],n;

int main()
{
	n = read();
	REP(i,n) REP(j,n) G[i][j] = read();
	int maxv = (1 << n) - 1,e1,e2;
	for (int i = 1; i <= n; i++)
		f[1 << i - 1][i] = G[1][i];
	for (int s = 2; s <= maxv; s += 2){
		for (int i = 1; i <= n; i++){
			e1 = 1 << i - 1;
			if ((e1 | s) == s){
				for (int j = 1; j <= n; j++){
					e2 = 1 << j - 1;
					if (j != i && (e2 | s) != s){
						if (!f[e2 | s][j]) f[e2 | s][j] = f[s][i] + G[i][j];
						else f[e2 | s][j] = min(f[e2 | s][j],f[s][i] + G[i][j]);
					}
				}
			}
		}
	}
	cout<<f[maxv][1]<<endl;
	return 0;
}

原文地址:https://www.cnblogs.com/Mychael/p/8282850.html