思路:一个很裸的0/1规划的题,没接触过的话很难会朝图论的方面去想,从前两个条件其实就是点1的出度为1,点n的入度为1,然后其他点的出度等于入度,边权就是它的费用,那么建图然后最短路就可以了,这里比较坑的是由于只说了出度为1,但入度不知道,所以可能存在两个环,从1出发回到1,从n出发回到n的情况
#include <iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
#define inf 1e9
const int maxn = 400;
int n,mp[maxn][maxn];
int d[maxn],inq[maxn];
int spfa(int s,int t,int &res)
{
queue<int>q;
for(int i = 0;i<=n;i++)
d[i]=inf;
memset(inq,0,sizeof(inq));
d[s]=0;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
inq[u]=0;
for(int i = 0;i<n;i++)
{
if(s!=u && i==s)
res = min(res,mp[u][i]+d[u]);
if(d[i]>d[u]+mp[u][i])
{
d[i]=d[u]+mp[u][i];
if(!inq[i])
{
q.push(i);
inq[i]=1;
}
}
}
}
return d[t];
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
scanf("%d",&mp[i][j]);
int res1 = inf;
int ans = spfa(0,n-1,res1);
int res2 = inf;
spfa(n-1,0,res2);
printf("%d\n",min(ans,res1+res2));
}
}