Problem Description
Given a n*n matrix Cij (1<=i,j<=n),We want to find a n*n matrix Xij (1<=i,j<=n),which is 0 or 1.
Besides,Xij meets the following conditions:
1.X12+X13+...X1n=1
2.X1n+X2n+...Xn-1n=1
3.for each i (1<i<n), satisfies ∑Xki (1<=k<=n)=∑Xij (1<=j<=n).
For example, if n=4,we can get the following equality:
X12+X13+X14=1
X14+X24+X34=1
X12+X22+X32+X42=X21+X22+X23+X24
X13+X23+X33+X43=X31+X32+X33+X34
Now ,we want to know the minimum of ∑Cij*Xij(1<=i,j<=n) you can get.
For sample, X12=X24=1,all other Xij is 0.
Besides,Xij meets the following conditions:
1.X12+X13+...X1n=1
2.X1n+X2n+...Xn-1n=1
3.for each i (1<i<n), satisfies ∑Xki (1<=k<=n)=∑Xij (1<=j<=n).
For example, if n=4,we can get the following equality:
X12+X13+X14=1
X14+X24+X34=1
X12+X22+X32+X42=X21+X22+X23+X24
X13+X23+X33+X43=X31+X32+X33+X34
Now ,we want to know the minimum of ∑Cij*Xij(1<=i,j<=n) you can get.
Hint
For sample, X12=X24=1,all other Xij 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 Cij(0<=Cij<=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 Cij(0<=Cij<=100000).
Output
For each case, output the minimum of ∑Cij*Xij 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;
}
本文探讨了一个特定的矩阵寻径问题,通过分析条件限制,将问题转化为图论中的最短路径问题,并提出了一种改进的Dijkstra算法及SPFA算法来解决这一问题。文中详细解释了算法实现过程及核心思想。
703

被折叠的 条评论
为什么被折叠?



