#include <bits/stdc++.h> using namespace std; const int MX=110010,MS=(1<<16)-1; int n,i,k,MSK,cnt,x,fi,fr,q[MX],was[MX],ed[MX],bc[MS+1],b[MX],bts[MX],a[MX][MX/32]; vector<int> g[MX],o[MX]; long long res; bool cmp(int i, int j) { return (b[i]!=0 && (b[j]==0 || b[i]<b[j])); } int main() { for (i=1; i<=MS; i++) bc[i]=bc[i/2]+(i&1); scanf("%d",&n); for (i=0; i<n; i++) { scanf("%d",&cnt); g[x].resize(cnt); while (cnt--) { scanf("%d",&g[x][i]); --g[x][i]; o[g[x][i]].push_back(i); } } MSK=(n-1)/32+1; for (i=1; i<=n; i++) { sort(g[i].begin(),g[i].end(),cmp); fi=true; for (int j: g[i]) if (j<=i) { if (fi) { for (k=0; k<MSK; ++k) a[i][k]=a[j][k]; } else { if ((a[i][j/32]>>(j%32))&1) continue; for (k=0; k<MSK; ++k) a[i][k]&=a[j][k]; } } a[i][i/32]|=(1<<(i%32)); ed[i]=-1; was[i]=i; q[fi=0]=i; fr=1; while (fi<fr) { x=q[fi++]; res-=bts[x]; for (bts[x]=k=0; k<MSK; ++k) { a[x][k]&=a[i][k]; bts[x]+=bc[a[x][k]&MS]; bts[x]+=bc[a[x][k]>>16]; } res+=bts[x]; for (int j: o[x]) { if (was[j]!=i) { was[j]=i; ed[j]=g[j].size(); } if (--ed[j]==0) q[fr++]=j; } } printf("%lld%c",res,(i==n)?'\n':' '); } return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #include <bits/stdc++.h> using namespace std; const int MX=110010,MS=(1<<16)-1; int n,i,k,MSK,cnt,x,fi,fr,q[MX],was[MX],ed[MX],bc[MS+1],b[MX],bts[MX],a[MX][MX/32]; vector<int> g[MX],o[MX]; long long res; bool cmp(int i, int j) { return (b[i]!=0 && (b[j]==0 || b[i]<b[j])); } int main() { for (i=1; i<=MS; i++) bc[i]=bc[i/2]+(i&1); scanf("%d",&n); for (i=0; i<n; i++) { scanf("%d",&cnt); g[x].resize(cnt); while (cnt--) { scanf("%d",&g[x][i]); --g[x][i]; o[g[x][i]].push_back(i); } } MSK=(n-1)/32+1; for (i=1; i<=n; i++) { sort(g[i].begin(),g[i].end(),cmp); fi=true; for (int j: g[i]) if (j<=i) { if (fi) { for (k=0; k<MSK; ++k) a[i][k]=a[j][k]; } else { if ((a[i][j/32]>>(j%32))&1) continue; for (k=0; k<MSK; ++k) a[i][k]&=a[j][k]; } } a[i][i/32]|=(1<<(i%32)); ed[i]=-1; was[i]=i; q[fi=0]=i; fr=1; while (fi<fr) { x=q[fi++]; res-=bts[x]; for (bts[x]=k=0; k<MSK; ++k) { a[x][k]&=a[i][k]; bts[x]+=bc[a[x][k]&MS]; bts[x]+=bc[a[x][k]>>16]; } res+=bts[x]; for (int j: o[x]) { if (was[j]!=i) { was[j]=i; ed[j]=g[j].size(); } if (--ed[j]==0) q[fr++]=j; } } printf("%lld%c",res,(i==n)?'\n':' '); } return 0; } |