HDU 4370 0 or 1(最短路)

本文介绍了一种将0/1规划问题转化为图论中的最短路径问题的方法,通过构建特定的图结构并利用SPFA算法求解最小费用流,以此解决特定矩阵中的元素选择问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:一个很裸的0/1规划的题,没接触过的话很难会朝图论的方面去想,从前两个条件其实就是点1的出度为1,点n的入度为1,然后其他点的出度等于入度,边权就是它的费用,那么建图然后最短路就可以了,这里比较坑的是由于只说了出度为1,但入度不知道,所以可能存在两个环,从1出发回到1,从n出发回到n的情况


#include<bits/stdc++.h>
using namespace std;
#define inf 1e9
const int maxn = 400;
int n,mp[maxn][maxn];
int d[maxn],inq[maxn];
int spfa(int s,int t,int &res)
{
	queue<int>q;
	for(int i = 0;i<=n;i++)
		d[i]=inf;
	memset(inq,0,sizeof(inq));
	d[s]=0;
	q.push(s);
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		inq[u]=0;
		for(int i = 0;i<n;i++)
		{
			if(s!=u && i==s)
				res = min(res,mp[u][i]+d[u]);
			if(d[i]>d[u]+mp[u][i])
			{
				d[i]=d[u]+mp[u][i];
				if(!inq[i])
					q.push(i);
				inq[i]=1;
			}
		}
	}
	return d[t];
}

int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		for(int i = 0;i<n;i++)
			for(int j = 0;j<n;j++)
				scanf("%d",&mp[i][j]);
		int res1 = inf;
		int ans = spfa(0,n-1,res1);
		int res2 = inf;
		spfa(n-1,0,res2);
		printf("%d\n",min(ans,res1+res2));
	}
}


Description

Given a n*n matrix C ij (1<=i,j<=n),We want to find a n*n matrix X ij (1<=i,j<=n),which is 0 or 1. 

Besides,X ij meets the following conditions: 

1.X 12+X 13+...X 1n=1 
2.X 1n+X 2n+...X n-1n=1 
3.for each i (1<i<n), satisfies ∑X ki (1<=k<=n)=∑X ij (1<=j<=n). 

For example, if n=4,we can get the following equality: 

12+X 13+X 14=1 
14+X 24+X 34=1 
12+X 22+X 32+X 42=X 21+X 22+X 23+X 24 
13+X 23+X 33+X 43=X 31+X 32+X 33+X 34 

Now ,we want to know the minimum of ∑C ij*X ij(1<=i,j<=n) you can get. 
Hint

For sample, X 12=X 24=1,all other X ij is 0. 

Input

The input consists of multiple test cases (less than 35 case). 
For each test case ,the first line contains one integer n (1<n<=300). 
The next n lines, for each lines, each of which contains n integers, illustrating the matrix C, The j-th integer on i-th line is C ij(0<=Cij<=100000).

Output

For each case, output the minimum of ∑C ij*X ij you can get. 

Sample Input

4
1 2 4 10
2 0 1 1
2 2 0 5
6 3 1 2

Sample Output

3


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值