poj 1603 Risk_spfa向前星

poj终于到100题,贴个代码纪念一下,hdu 到400题再贴

题意:有20个城市,接下来有19行告诉你,i城市与n个城市相连,图是双向的,然后叫你求x到y的最小经过几个城市

#include <iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define N 210
#define INF 0xffffff
int num;
struct node{
	int u,v,next,d;
}edge[N],tedge[30];
int head[N],flag[N],dist[N];
void add(int u,int v,int d){
	edge[num].v=v;
	edge[num].d=d;
	edge[num].next=head[u];
	head[u]=num++;
}
int spfa(int x,int y){
	int i,sum=0;
	for(i=1;i<=20;i++){
		dist[i]=INF;
		flag[i]=0;
	}
	dist[x]=0;
	queue<int>q;
	q.push(x);
	while(!q.empty()){
		int tmp=q.front();
		q.pop();
		flag[tmp]=0;
		for(i=head[tmp];i!=-1;i=edge[i].next){
			int v=edge[i].v;
			int d=edge[i].d;
			if(dist[tmp]+d<dist[v]){
				dist[v]=dist[tmp]+d;
				if(!flag[v]){
					q.push(v);
					flag[v]=1;
				}
			}
		}
	}
	return dist[y];
}
int main(int argc, char** argv) {
	int Case=1,n,i,x,j,y,ans;
	while(scanf("%d",&n)!=EOF){
		printf("Test Set #%d\n",Case++);
		num=0;
		memset(head,-1,sizeof(head));
		for(i=0;i<n;i++){
			scanf("%d",&x);
			add(1,x,1);
			add(x,1,1);
		}
		for(i=2;i<=19;i++){
			scanf("%d",&n);
			for(j=0;j<n;j++){
				scanf("%d",&x);
				add(i,x,1);
				add(x,i,1);
			}
		}
		scanf("%d",&n);
		for(i=0;i<n;i++){
			scanf("%d%d",&x,&y);
			ans=spfa(x,y);
			printf("%d to %d: %d\n",x,y,ans);
		}
		printf("\n");
	}
	return 0;
}


你可能感兴趣的:(SPFA)