最短路之SPFA(单源)HDU 1317
#include <iostream> #include<cstdio> #include<cstring> #include<cmath> #include<queue> #define N 110 #define INF 0x7ffffff using namespace std; int n,val[N],mp[N][N],d[N],v[N],num[N],r[N][N]; void floyd() { for(int k=1;k<=n;k++) for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) r[i][j]=max(r[i][j],r[i][k]&r[k][j]); } int spfa(int s,int t) { for(int i=1;i<=n;i++) { num[i]=0; d[i]=-INF; v[i]=0; } queue<int> q; q.push(s); v[s]=1; d[s]=100; num[s]++; while(!q.empty()) { int c=q.front(); q.pop(); v[c]=0; for(int i=1;i<=n;i++) { if(d[c]+mp[c][i]>0&&d[i]<d[c]+mp[c][i]) { d[i]=d[c]+mp[c][i]; if(!v[i]) { if(++num[i]>=n) return r[i][t]; v[i]=1,q.push(i); } } } } if(d[t]>0) return 1; return 0; } int main() { while(~scanf("%d",&n)&&n!=-1) { memset(mp,0,sizeof(mp)); memset(r,0,sizeof(r)); for(int i=1;i<=n;i++) { int nn; scanf("%d%d",&val[i],&nn); for(int j=0;j<nn;j++) { int c; scanf("%d",&c); mp[i][c]=1; r[i][c]=1; } } for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { if(mp[i][j]==0) mp[i][j]=-INF; else mp[i][j]*=val[j]; } floyd(); if(spfa(1,n)) cout<<"winnable"<<endl; else cout<<"hopeless"<<endl; } }