The shortest path.
The first 19 rows are adjacent, undirected graphs, and the last query is the shortest.
Floyd is the simplest. But I use spfa. In fact, it is to find the most short circuit, but there is no distance, but each time + 1.
Note that the last line needs to output a blank line. Contribute to the release of PE.
#include<cstdio>#include<cstring>#include<string>#include<queue>#include<algorithm>#include<map>#include<stack>#include<iostream>#include<list>#include<set>#include<cmath>#define INF 0x7fffffff#define eps 1e-6#define LL long longusing namespace std;vector<int>g[21];int dis[21][21];bool sp[21];int n,m;void SPFA(int start){ queue<int>q; bool vis[21]; memset(vis,0,sizeof(vis)); q.push(start); dis[start][start]=0; vis[start]=1; while(!q.empty()) { int u=q.front();q.pop(); vis[u]=0; for(int j=0;j<g[u].size();j++) { int v=g[u][j]; if(dis[start][v]>dis[start][u]+1) { dis[start][v]=dis[start][u]+1; if(!vis[v]) { vis[v]=1; q.push(v); } } } }}int main(){ int nn=1; while(scanf("%d",&m)!=EOF) { for(int i=1;i<21;i++) g[i].clear(),sp[i]=0; int v; while(m--) { scanf("%d",&v); g[1].push_back(v); g[v].push_back(1); } for(int i=2;i<20;i++) { scanf("%d",&m); while(m--) { scanf("%d",&v); g[i].push_back(v); g[v].push_back(i); } } for(int i=1;i<21;i++) for(int j=1;j<21;j++) dis[i][j]=INF; scanf("%d",&m); int start,thend; printf("Test Set #%d\n",nn++); while(m--) { scanf("%d%d",&start,&thend); if(!sp[start]) { SPFA(start); sp[start]=1; } printf("%d to %d: %d\n",start,thend,dis[start][thend]); } printf("\n"); }}
Poj 1603 risk