UVA 11324 The Largest Clique 强连通分量 DP
找强连通分量,缩点,DP
//#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<iostream> #include<sstream> #include<cmath> #include<climits> #include<string> #include<map> #include<queue> #include<vector> #include<stack> #include<set> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; #define pb(a) push(a) #define INF 0x1f1f1f1f #define lson idx<<1,l,mid #define rson idx<<1|1,mid+1,r #define PI 3.1415926535898 template<class T> T min(const T& a,const T& b,const T& c) { return min(min(a,b),min(a,c)); } template<class T> T max(const T& a,const T& b,const T& c) { return max(max(a,b),max(a,c)); } void debug() { #ifdef ONLINE_JUDGE #else freopen("d:\\in1.txt","r",stdin); freopen("d:\\out1.txt","w",stdout); #endif } int getch() { int ch; while((ch=getchar())!=EOF) { if(ch!=' '&&ch!='\n')return ch; } return EOF; } struct Edge { int u,v; }; const int maxn=1005; vector<int> g[maxn]; int pre[maxn],low[maxn],sccno[maxn]; int dfs_clock,scc_cnt; stack<int> s; void dfs(int u) { s.push(u); low[u]=pre[u]=++dfs_clock; for(int i=0;i<g[u].size();i++) { int v=g[u][i]; if(!pre[v]) { dfs(v); low[u]=min(low[u],low[v]); }else if(!sccno[v]) { low[u]=min(low[u],pre[v]); } } if(low[u]==pre[u]) { scc_cnt++; while(1) { int x=s.top();s.pop(); sccno[x]=scc_cnt; if(x==u)break; } } } void tarjan(int n) { memset(sccno,0,sizeof(sccno)); memset(pre,0,sizeof(pre)); dfs_clock=scc_cnt=0; for(int i=1;i<=n;i++) if(!pre[i])dfs(i); } vector<int> gscc[maxn]; int w[maxn]; int deg0[maxn]; void construct(int n) { for(int i=1;i<=scc_cnt;i++) { gscc[i].clear(); deg0[i]=1; } for(int i=1;i<=n;i++) for(int j=0;j<g[i].size();j++) { int v=g[i][j]; if(sccno[i]!=sccno[v]) { gscc[sccno[i]].push_back(sccno[v]); deg0[sccno[v]]=0; } } memset(w,0,sizeof(w)); for(int i=1;i<=n;i++) w[sccno[i]]++; } int dp[maxn]; int f(int u) { if(dp[u]>=0)return dp[u]; dp[u]=w[u]; for(int i=0;i<gscc[u].size();i++) { int v=gscc[u][i]; dp[u]=max(dp[u],f(v)+w[u]); } return dp[u]; } int main() { int t; scanf("%d",&t); for(int ca=1;ca<=t;ca++) { int n,m; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++)g[i].clear(); for(int i=1;i<=m;i++) { int u,v; scanf("%d%d",&u,&v); g[u].push_back(v); } tarjan(n); construct(n); int res=0; memset(dp,-1,sizeof(dp)); for(int i=1;i<=scc_cnt;i++) if(deg0[i]) { res=max(res,f(i)); } printf("%d\n",res); } return 0; }