来两遍 $BFS,$ 都贪心一下即可.
#include <bits/stdc++.h> #define maxn 300009 using namespace std; void setIO(string s) { string in=s+".in"; freopen(in.c_str(),"r",stdin); } queue<int>Q; int n,m,s,edges,nn=0; int hd[maxn],to[maxn<<1],nex[maxn<<1],val[maxn<<1],vis[maxn],mk[maxn<<1],idx[maxn<<1],ou[maxn<<1]; void addedge(int u,int v,int c) { nex[++edges]=hd[u],hd[u]=edges,to[edges]=v,val[edges]=c; } void solve1() { memset(vis,0,sizeof(vis)); vis[s]=1; Q.push(s); while(!Q.empty()) { int u=Q.front();Q.pop(); for(int i=hd[u];i;i=nex[i]) { int v=to[i]; if(val[i]) { if(val[i]==1) ou[idx[i]]=0; else ou[idx[i]]=1; continue; } if(!vis[v]) { Q.push(v); vis[v]=1; } } } int cnt=0; for(int i=1;i<=n;++i) if(vis[i]) ++cnt; printf("%d ",cnt); for(int i=1;i<=nn;++i) if(ou[i]) printf("+"); else printf("-"); printf(" "); } void solve2() { memset(vis,0,sizeof(vis)); vis[s]=1; Q.push(s); int cc=0; while(!Q.empty()) { int u=Q.front();Q.pop(); for(int i=hd[u];i;i=nex[i]) { int v=to[i]; if(!vis[v]) { Q.push(v); vis[v]=1; if(val[i])mk[i]=1; } } } int cnt=0; for(int i=1;i<=n;++i) if(vis[i]) ++cnt; printf("%d ",cnt); for(int i=1;i<=edges;++i) { if(mk[i]==1) { if(val[i]==1) ou[idx[i]]=1; else ou[idx[i]]=0; } } for(int i=1;i<=nn;++i) if(ou[i]) printf("+"); else printf("-"); printf(" "); memset(ou,0,sizeof(ou)); } int main() { // setIO("input"); scanf("%d%d%d",&n,&m,&s); for(int i=1;i<=m;++i) { int t,u,v; scanf("%d%d%d",&t,&u,&v); if(t==1) addedge(u,v,0); else addedge(u,v,1),idx[edges]=++nn,addedge(v,u,2),idx[edges]=nn; } solve2(); solve1(); return 0; }