最短路SPFA—0 or 1(HDU - 4370)

题目链接:>_>

题目:0 or 1

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

题意:

求min((1号点到n号点的花费),(1号点经过其它点成环,n号点经过其它点成环,这两个环的花费之和))。

AC代码:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
#define inf 0x3f3f3f3f
int mp[305][305];
int dis[10005];
int vis[10005];
int n;
priority_queue<int>q;
void spfa(int start) {
	for (int i = 0; i < n; i++) {
		if (i == start) {
			dis[i] = inf;
			vis[i] = 0;
		}
		else {
			q.push(i);
			dis[i] = mp[start][i];
			vis[i] = 1;
		}
	}
	while (!q.empty()) {
		int u = q.top();
		q.pop();
		for (int i = 0; i < n; i++) {
			if (dis[i] > dis[u] + mp[u][i]) {
				dis[i] = dis[u] + mp[u][i];
				if (!vis[i]) {
					vis[i] = 1;
					q.push(i);
				}
			}
		}
		vis[u] = 0;
	}
}
int main() {
	while (~scanf("%d", &n)) {
		for (int i = 0; i < n; i++)for (int j = 0; j < n; j++)scanf("%d", &mp[i][j]);
		int i, j;
		spfa(0);
		int ans1, ans2;
		ans1 = dis[n-1];
		ans2 = dis[0];
		spfa(n - 1);
		ans2 += dis[n - 1];
		cout << min(ans1, ans2) << endl;
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值