POJ3311(状态压缩DP+Floyd)

不知道为什么min写成#define min(x,y) ((x)<(y)?(x):(y))用G++交就一直WA,用C++交就过了。

最后还是写成函数的形式好了。

因为顶点可以重复通过要先做Floyd处理一遍。

#include <iostream>
#include <cstring>
#include <cstdio>
#define INF 0xffffff

using namespace std;

int dis[11][11];
int dp[1<<11][11];
int n;

int min(int x,int y)
{
	return x<y?x:y;
}
void floyd()
{
	int i,j,k;
	for (k=0;k<=n;k++)
		for (i=0;i<=n;i++)
			for (j=0;j<=n;j++)
				if (dis[i][k]+dis[k][j]<dis[i][j])
					dis[i][j]=dis[i][k]+dis[k][j];
}

int main()
{
	int i,j;
	while (1)
	{
		scanf("%d",&n);
		if (!n) break;

		for (i=0;i<=n;i++)
			for (j=0;j<=n;j++)
				scanf("%d",&dis[i][j]);
		floyd();

		int state;
		for (state=1;state<1<<n;state++)
      for (i=1;i<=n;i++)
      {
      	dp[state][i]=INF;
      	if (state&(1<<(i-1)))
      	{
      		if ( state == 1<<(i-1))
      			dp[state][i]=dis[0][i];
      		else
      		{
						for (j=1;j<=n;j++)
							if (i!=j && (state&(1<<(j-1))))
								dp[state][i]=min(dp[state^(1<<(i-1))][j]+dis[j][i],dp[state][i]);
      		}
      	}
      }

		int ans=INF;
		for (i=1;i<=n;i++)
			ans=min(dp[state-1][i]+dis[i][0],ans);
		printf("%d\n",ans);
	}
}

为什么不用维护dp[state][0]呢?

因为dp[state][0]表示从0开始经过state中的那些点又回到0,dp[state][i](1<=i<=n)的更新不会用到dp[state^(1<<(i-1))][0],如果可以通过0更新,则说明可以通过路径x->0->i更新(x是state^(1<<(i-1))中的某个点),而实际上我们已经用floyd处理过了,dis[x][i]实际上已经被优化为x->0->i的更短的路径了,所以dp[state][i]的更新利用dp[state^(1<<(i-1))][x]来更新即可,不必是dp[state^(1<<(i-1))][0]。


若维护dp[state][0]可以这么写,也是没问题的。

#include <iostream>
#include <cstring>
#include <cstdio>
#define INF 0xffffff

using namespace std;

int dis[11][11];
int dp[1 << 11][11];
int n;

int min(int x, int y)
{
	return x < y ? x : y;
}
void floyd()
{
	int i, j, k;
	for (k = 0; k <= n; k++)
		for (i = 0; i <= n; i++)
			for (j = 0; j <= n; j++)
				if (dis[i][k] + dis[k][j] < dis[i][j])
					dis[i][j] = dis[i][k] + dis[k][j];
}

int main()
{
	int i, j;
	while (1)
	{
		scanf("%d", &n);
		if (!n)
			break;

		for (i = 0; i <= n; i++)
			for (j = 0; j <= n; j++)
				scanf("%d", &dis[i][j]);
		floyd();

		int state;
		for (state = 1; state < 1 << n; state++)
		{
			for (i = 1; i <= n; i++)
			{
				dp[state][i] = INF;
				if (state & (1 << (i - 1)))
				{
					if (state == 1 << (i - 1))
						dp[state][i] = dis[0][i];
					else
					{
						dp[state][i] = min(dp[state ^ (1 << (i - 1))][0] + dis[0][i], dp[state][i]);
						for (j = 1; j <= n; j++)
							if (i != j && (state & (1 << (j - 1))))
								dp[state][i] = min(dp[state ^ (1 << (i - 1))][j] + dis[j][i], dp[state][i]);
					}
				}
			}
			dp[state][0] = INF;
			for (i = 1; i <= n; i++)
				if (state & (1 << (i - 1)))
					dp[state][0] = min(dp[state][0], dp[state][i] + dis[i][0]);
		}

		printf("%d\n", dp[state - 1][0]);
	}
}



你可能感兴趣的:(POJ3311(状态压缩DP+Floyd))