Problem 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:
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.
For sample, X 12=X 24=1,all other X ij is 0.
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).
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.
分析:
从图的角度来看,条件一等价于点1仅有一个出度,条件二等价于点n仅有一个入度,条件三等价于点2到n-1每个点出度与入度相等。
对应了两种情况,一是从1到n求一个最短路,这必然满足条件。
还有一种情况是,如果图中1和n相当于是不连通的,即从1到n的代价太大。这是可以考虑一个包含1的环和一个包含n的环。
适当更改dijkstra算法:将始点直接相连的点的距离更新,dist[begin]=INF,然后开始循环,这样dist[begin]即为过begin的最小环的花费,其余点依旧是begin到各点的最短路。具体看代码。
事实上spfa算法也可以做类似的改造,将始点直接相连的点的距离更新并将这些全部加入队列,dist[begin]=INF,然后运行算法,也可以求得同样的结果,通话时也能处理负边和判断负环。
dijkstra代码:
#include<cstdio>
#include<cstring>
using namespace std;
#define INF (1<<30)
#define min(x,y) (x<y?x:y)
int C[305][305],dist[305],n;
bool vis[305];
void dijkstra(int from,int to){
for(int i=1;i<=n;++i){dist[i]=C[from][i];vis[i]=false;}
dist[from]=INF;int u,val;
for(int i=1;i<=n;++i){val=INF;u=0;
for(int j=1;j<=n;++j){
if(!vis[j]&&dist[j]<val){
val=dist[j];u=j;
}
}
if(u==0||u==to) break;
vis[u]=true;
for(int j=1;j<=n;++j){
if(!vis[j]) dist[j]=min(dist[j],dist[u]+C[u][j]);
}
}
}
int main(){
int loop1,loop2,ans;
while(scanf("%d",&n)!=EOF){
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j) scanf("%d",&C[i][j]);
}
dijkstra(1,n);ans=dist[n];
dijkstra(1,1);loop1=dist[1];
dijkstra(n,n);loop2=dist[n];
printf("%d\n",min(ans,loop1+loop2));
}
return 0;
}