HDU 4370 0 or 1(思维最短路)

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. 

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

一开始没思路,看了题解还是是不懂.....

首先分析一波题..

我们将这个矩阵看作一个链接矩阵;

所以对应条件就变成

1:起点出度为一

2.终点入度为一

3.除了起点终点外其余点的出度等于入度

0为不选这条边,1为选择这条边,所以 ∑C ij*X ij变为从1到n的最短路 或 从1 n开始俩个自环的和 的最小值

所以..跑spfa就可以了

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<set>

#define mem(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f

const int maxn=1e4+5;

using namespace std;

int nmap[305][305];

int d[305],vis[305],n;

void spfa(int st)
{
    queue<int>q;
    mem(vis,0);
    for(int i=1;i<=n;i++)
    {
        d[i]=nmap[st][i];
        if(i!=st)
        {
            q.push(i);
            vis[i]=1;
        }
        else 
        {
            vis[i]=0;
        }
    }
    d[st]=inf;
    while(!q.empty())
    {
        int now=q.front();
        q.pop();
        vis[now]=0;
        for(int i=1;i<=n;i++)
        {
            int u=now,v=i,w=nmap[now][i];
            if(u==i) continue;
            if(d[v]>d[u]+w)
            {
                d[v]=d[u]+w;
                if(!vis[v])
                {
                    vis[v]=1;
                    q.push(v);
                }
            }
        }
    }
}

int main(){
    while(~scanf("%d",&n))
    {
        mem(nmap,0);
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&nmap[i][j]);
        spfa(1);
        int ans=d[1],minn=d[n];
        spfa(n);
        ans+=d[n];
        printf("%d\n",min(minn,ans));
    }
    return 0;
}

 

posted @ 2019-01-20 10:54  Minun  阅读(150)  评论(0编辑  收藏  举报