BZOJ1093 ZJOI2007最大半连通子图(缩点+dp)
发现所谓半连通子图就是缩点后的一条链之后就是个模板题了。注意缩点后的重边。写了1h+真是没什么救了。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> #include<vector> using namespace std; int read() { int x=0,f=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } #define N 100010 #define M 1000010 int n,m,P,p[N],p_new[N],dfn[N],low[N],stk[N],set[N],size[N],f[N],s[N],degree[N],q[N],top=0,cnt=0,t=0,ans=0; bool flag[N]; vector<int> a[N]; struct data{int to,nxt; }edge[M],edge_new[M]; void addedge(int x,int y){t++;edge[t].to=y,edge[t].nxt=p[x],p[x]=t;} void addedge_new(int x,int y){cnt++;edge_new[cnt].to=y,edge_new[cnt].nxt=p_new[x],p_new[x]=cnt;} void tarjan(int k) { dfn[k]=low[k]=++cnt; stk[++top]=k;flag[k]=1; for (int i=p[k];i;i=edge[i].nxt) if (!dfn[edge[i].to]) tarjan(edge[i].to),low[k]=min(low[k],low[edge[i].to]); else if (flag[edge[i].to]) low[k]=min(low[k],dfn[edge[i].to]); if (dfn[k]==low[k]) { t++; while (stk[top]!=k) { size[t]++; set[stk[top]]=t; flag[stk[top]]=0; top--; } size[t]++;set[k]=t;flag[k]=0;top--; } } void topsort() { int head=0,tail=0; for (int i=1;i<=n;i++) if (!degree[i]) q[++tail]=i; while (tail<n) { int x=q[++head]; for (int i=p[x];i;i=edge[i].nxt) { degree[edge[i].to]--; if (!degree[edge[i].to]) q[++tail]=edge[i].to; } } } void inc(int &x,int y){x+=y;if (x>=P) x-=P;} int main() { freopen("bzoj1093.in","r",stdin); freopen("bzoj1093.out","w",stdout); n=read(),m=read(),P=read(); for (int i=1;i<=m;i++) { int x=read(),y=read(); addedge(x,y); } t=0; for (int i=1;i<=n;i++) if (!dfn[i]) tarjan(i); cnt=0; for (int i=1;i<=n;i++) for (int j=p[i];j;j=edge[j].nxt) if (set[i]!=set[edge[j].to]) a[set[i]].push_back(set[edge[j].to]); n=t;memset(flag,0,sizeof(flag)); for (int i=1;i<=n;i++) { int s=a[i].size(); for (int j=0;j<s;j++) if (!flag[a[i][j]]) addedge_new(i,a[i][j]),flag[a[i][j]]=1,degree[a[i][j]]++; for (int j=0;j<s;j++) flag[a[i][j]]=0; } memcpy(p,p_new,sizeof(p)); memcpy(edge,edge_new,sizeof(edge)); topsort(); for (int v=n;v>=1;v--) { int i=q[v]; s[i]=1; for (int j=p[i];j;j=edge[j].nxt) if (f[edge[j].to]>f[i]) f[i]=f[edge[j].to],s[i]=s[edge[j].to]; else if (f[edge[j].to]==f[i]) inc(s[i],s[edge[j].to]); f[i]+=size[i]; } for (int i=1;i<=n;i++) ans=max(ans,f[i]); int tot=0; for (int i=1;i<=n;i++) if (f[i]==ans) inc(tot,s[i]); cout<<ans<<endl<<tot; fclose(stdin);fclose(stdout); return 0; }