0 or 1 HDU - 4370 思维最短路

0 or 1 HDU - 4370

Given a nn matrix C ij (1<=i,j<=n),We want to find a nn 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:
X 12+X 13+X 14=1
X 14+X 24+X 34=1
X 12+X 22+X 32+X 42=X 21+X 22+X 23+X 24
X 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<=C ij<=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

思路:
联想到图的矩阵存储
X 12+X 13+X 14=1 要求点1的出度为1,不存在点1指向1的情况
X 14+X 24+X 34=1 要求点n的入度为1,不存在点n指向n的情况
X 12+X 22+X 32+X 42=X 21+X 22+X 23+X 24 其余点的出度与入度相同
X 13+X 23+X 33+X 43=X 31+X 32+X 33+X 34
X矩阵的0代表走这条边,1代表不走这条边,转化为求顶点1到n的最短路径
点1出度为一(条件一),那么一定要到另一个点,如果到n则求1到n的最短路,如果到其他点,由于其他点的出入度要求相同(条件三),这时需要该点一定有一条出去的边,如果到n则有1到n的最短路,如果不到n点则必然有1–>1的闭环,当有1–>1的自环时,点n的入度为一,则必有一个点指向n,并且只能是点1,n以外的其他点,由于其他点的出入度要求相同(条件三),此时必有n–>n的闭环。
所以一定有1到n的路或 有n的自环和1的自环。
所以需要计算1到n的最短路,1自环和n自环的总值,两者最小就为答案。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int inf = 0x3f3f3f3f;
int n, cir, ans;
int g[305][305], d[305];
bool vis[305];

void dijikstra(int s) {
	memset(d, 0x3f, sizeof(d));
	memset(vis, false, sizeof(vis));
	d[s] = 0;
	for(int i = 1; i <= n; i++) {
		int t = -1;
		for(int j = 1; j <= n; j++) {
			if(!vis[j] && (t == -1 || d[t] > d[j])) t = j;
		}
		vis[t] = true;
		for(int j = 1; j <= n; j++) {
			d[j] = min(d[j], d[t] + g[t][j]);
			if(j == s && t != s) cir = min(cir, d[t] + g[t][j]); //当j为起点,t不为起点时
		}
	}	
}

int main() {
	while(~scanf("%d", &n)) {
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) {
				scanf("%d", &g[i][j]);
			}
		}
		cir = inf;
		dijikstra(1);
		ans = d[n];
		int t = cir;//1的子环 
		cir = inf;
		dijikstra(n);
		t += cir;//加上n的子环
		printf("%d\n", min(ans, t)); 
	}
	return 0;	
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值