截图于https://www.cnblogs.com/five20/
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 using namespace std; 6 const int maxn=1e6+7; 7 int n,k,num,head[maxn],d[maxn],cnt[maxn]; 8 bool inq[maxn]; 9 queue<int>q; 10 struct Edge{ 11 int next,to,dis; 12 }edge[maxn*2]; 13 void addedge(int from,int to,int dis){ 14 edge[++num].next=head[from]; 15 edge[num].to=to; 16 edge[num].dis=dis; 17 head[from]=num; 18 } 19 bool spfa(){ 20 memset(d,2147483647,sizeof(d)); 21 d[0]=0;inq[0]=true;q.push(0);cnt[0]++; 22 while(!q.empty()){ 23 int u=q.front();q.pop();inq[u]=false; 24 for(int i=head[u];i;i=edge[i].next){ 25 int v=edge[i].to; 26 if(d[v]<d[u]+edge[i].dis){ 27 d[v]=d[u]+edge[i].dis; 28 if(!inq[v]){ 29 q.push(v); 30 inq[v]=true; 31 cnt[v]++; 32 if(cnt[v]>n) return false; 33 } 34 } 35 } 36 } 37 return true; 38 } 39 int main(){ 40 cin>>n>>k; 41 for(int i=1;i<=k;i++){ 42 int opt,u,v;cin>>opt>>u>>v; 43 if(opt==1){ 44 addedge(u,v,0); 45 addedge(v,u,0); 46 } 47 if(opt==2){ 48 if(u==v) {cout<<-1<<endl;return 0;}//没有会TLE 49 else addedge(u,v,1); 50 } 51 if(opt==3){ 52 addedge(v,u,0); 53 } 54 if(opt==4){ 55 if(u==v) {cout<<-1<<endl;return 0;} 56 else addedge(v,u,1); 57 } 58 if(opt==5){ 59 addedge(u,v,0); 60 } 61 } 62 for(int i=n;i>=1;i--)//顺序会TLE 63 addedge(0,i,1); 64 if(!spfa()) cout<<-1<<endl; 65 else{ 66 long long ans=0;//1e5*1e5会爆int 67 for(int i=1;i<=n;i++){ 68 ans+=d[i]; 69 } 70 cout<<ans<<endl; 71 } 72 return 0; 73 }