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
这个题数组开成300少一个结果wa了,做题要注意循环的上下限
a. 求1到n的最短路径
b. 求以1为起点的最短环+以n为起点的最短环
结果为a,b中小的一个
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#define N 305
#define INF 0x3f3f3f3f
using namespace std;
int dis[N][N],res,r[N],flag[N],n;
void Initial(){
memset(r,INF,sizeof(r));
memset(flag,0,sizeof(flag));
res=0;
}
void Dij(int add){
r[add]=0;
while(1){
flag[add]=1;
for(int i=1;i<=n;i++){
if(flag[i]) continue;
r[i]=min( r[i],r[add]+dis[add][i] );
}
int minnum=INF;
int minid=-1;
for(int i=1;i<=n;i++){
if(flag[i]) continue;
if(minnum>r[i]){
minnum=r[i];
minid=i;
}
}
if(minid==-1) break;
add=minid;
}
}
int main()
{
while(~scanf("%d",&n)){
Initial();
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
scanf("%d",&dis[i][j]);
}
Dij(1);
res=r[n];
int x=INF,y=INF;
for(int i=2;i<=n;i++)
x=min( x,r[i]+dis[i][1] );
memset(r,INF,sizeof(r));
memset(flag,0,sizeof(flag));
Dij(n);
for(int i=1;i<n;i++)
y=min( y,r[i]+dis[i][n] );
res=min(res,x+y);
cout<<res<<endl;
}
return 0;
}