挺有意思的题目。
注意等式的条件。
等式1实际表示点1的出度为1,等式2实际表示点2的入度为1,等式表示其它点为中间点,入度和出度相等。
很容易转换成一条最短路。spfa直接可求,C即为邻接矩阵。
同时,可能存在1点出发,最终回到1点的环,从n点出发,最终回到n点的环。
/* 4370 */
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <deque>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <climits>
#include <cctype>
#include <cassert>
#include <functional>
#include <iterator>
#include <iomanip>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,1024000") #define sti set<int>
#define stpii set<pair<int, int> >
#define mpii map<int,int>
#define vi vector<int>
#define pii pair<int,int>
#define vpii vector<pair<int,int> >
#define rep(i, a, n) for (int i=a;i<n;++i)
#define per(i, a, n) for (int i=n-1;i>=a;--i)
#define clr clear
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define lson l, mid, rt<<1
#define rson mid+1, r, rt<<1|1 const int INF = 0x3f3f3f3f;
const int maxn = ;
int C[maxn][maxn];
int dis[maxn];
bool visit[maxn];
int n; void spfa(int s) {
queue<int> Q;
int u; rep(i, , n+) {
if (s == i) {
dis[i] = INF;
} else {
dis[i] = C[s][i];
visit[i] = true;
Q.push(i);
}
} while (!Q.empty()) {
u = Q.front();
Q.pop();
visit[u] = false;
rep(v, , n+) {
if (dis[v] > dis[u]+C[u][v]) {
dis[v] = dis[u] + C[u][v];
if (!visit[v]) {
visit[v] = true;
Q.push(v);
}
}
}
}
} void solve() {
int ans, tmp; spfa();
ans = dis[n];
tmp = dis[];
spfa(n);
tmp += dis[n]; ans = min(ans, tmp);
printf("%d\n", ans);
} int main() {
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif while (scanf("%d", &n)!=EOF) {
rep(i, , n+)
rep(j, , n+)
scanf("%d", &C[i][j]);
solve();
} #ifndef ONLINE_JUDGE
printf("time = %d.\n", (int)clock());
#endif return ;
}