2019-10-14 10:04:42

// ===================================
//   author: M_sea
//   website: http://m-sea-blog.com/
// ===================================
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#define re register
using namespace std;

int X=0,w=1; char c=getchar();
while (c<'0'||c>'9') { if (c=='-') w=-1; c=getchar(); }
while (c>='0'&&c<='9') X=X*10+c-'0',c=getchar();
return X*w;
}

const int N=100+10;
const int inf=0x3f3f3f3f;

int n,m;
vector<int> G[N],fG[N];
int dis[N][N];

struct node { int u1,u2,d; };
bool operator <(node a,node b) { return a.d>b.d; }
int dp[N][N];
inline void dijkstra() {
memset(dp,0x3f,sizeof(dp)),dp[1][1]=1;
priority_queue<node> Q; Q.push((node){1,1,1});
while (!Q.empty()) {
int u1=Q.top().u1,u2=Q.top().u2,d=Q.top().d; Q.pop();
if (d!=dp[u1][u2]) continue;
for (re int v:G[u1]) { int w=v!=u2;
if (d+w<dp[v][u2]) dp[v][u2]=d+w,Q.push((node){v,u2,d+w});
}
for (re int v:fG[u2]) { int w=v!=u1;
if (d+w<dp[u1][v]) dp[u1][v]=d+w,Q.push((node){u1,v,d+w});
}
if (u1!=u2&&d+dis[u1][u2]-1<dp[u2][u1])
dp[u2][u1]=d+dis[u1][u2]-1,Q.push((node){u2,u1,dp[u2][u1]});
}
}

int main() { int T=0;
memset(dis,0x3f,sizeof(dis));
for (re int i=1;i<=m;++i) {
G[u].push_back(v),fG[v].push_back(u);
}
for (re int k=1;k<=n;++k)
for (re int i=1;i<=n;++i)
for (re int j=1;j<=n;++j)
dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]);
printf("Network %d\n",++T);
if (dis[1][2]>=inf||dis[2][1]>=inf) puts("Impossible");
else dijkstra(),printf("Minimum number of nodes = %d\n",dp[2][2]);
puts("");
for (re int i=1;i<=n;++i) G[i].clear(),fG[i].clear();
}
return 0;
}
• star
首页