Problem B: The Largest Clique

Given a directed graph G, consider the following transformation. First, create a new graphT(G) to have the same vertex set as G. Create a directed edge betweentwo vertices u and v in T(G) if and only if there is a pathbetween u and v in G that follows the directed edges only in the forwarddirection. This graph T(G) is often called the transitive closure of G.
We define a clique in a directed graph as a set of vertices U such thatfor any two vertices u and v in U, there is a directededge either from u to v or from v to u (or both).The size of a clique is the number of vertices in the clique.
The number of cases is given on the first line of input. Each test case describes a graph G.It begins with a line of two integersn and m, where 0 ≤ n ≤ 1000 is the number ofvertices of Gand 0 ≤ m ≤ 50,000 is the number of directed edges of G.The vertices of G are numbered from 1 to n.The following m lines contain two distinct integers u and vbetween 1 and n which definea directed edge from u to v in G.
For each test case, output a single integer that is the size of the largest clique in T(G).
Sample input
1 5 5 1 2 2 3 3 1 4 1 5 2
Output for sample input
4
题意:“给一张有向图G,求一个结点数最大的结点集,使得该结点集中任意两个结点u和v满足:要么u可以到达v,要么v可以到达u(u和v相互可达也可以)。”
分析:强连通分量一定可以满足。缩点后变为SCC(强连通分量)图的DAG。动态规划求最大权值路径。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<stack>
#include<queue>
#include<vector>
#include<climits>
using namespace std;
const int N = 1001;
int INF = INT_MAX;
typedef long long LL;
vector<int>G[N],G2[N];
int low[N],dfn[N],vis[N],inst[N],sum[N];
stack<int>st;
int num, tim;
int bel[N];
int d[N];
void tarjan(int u)
{
vis[u] = 1;
low[u] = dfn[u] = ++tim;
inst[u] = 1; st.push(u);
for(int i=0; i<G[u].size(); i++) {
int v = G[u][i];
if(!vis[v]) {
tarjan(v);
low[u] = min(low[u],low[v]);
}
else if(inst[v]) low[u] = min(low[u],dfn[v]);
}
if(low[u] == dfn[u]) {
int j;
num++;
do {
j = st.top(); st.pop();
bel[j] = num;
inst[j] = 0;
sum[num]++;
} while(j!=u);
}
}
int dp(int u)
{
if(d[u]) return d[u];
d[u] = sum[u];
for(int i=0; i<G2[u].size(); i++) {
int v = G2[u][i];
d[u] = max(d[u],sum[u]+dp(v));
}
return d[u];
}
int main()
{
int i,j,k,m,n,T;
scanf("%d",&T);
while(T--) {
scanf("%d %d",&n,&m);
for(i=1; i<=n; i++) G[i].clear();
while(m--) {
scanf("%d %d",&i,&j);
G[i].push_back(j);
}
memset(vis,0,sizeof(vis));
memset(sum,0,sizeof(sum));
memset(inst,0,sizeof(inst));
while(!st.empty()) st.pop();
num = tim = 0;
for(i=1; i<=n; i++)
if(!vis[i]) tarjan(i);
for(i=1; i<=num; i++) G2[i].clear();
for(i=1; i<=n; i++)
for(j=0; j<G[i].size(); j++) {
int v = G[i][j];
if(bel[i] != bel[v]) G2[bel[i]].push_back(bel[v]);
}
int ans = 0;
memset(d,0,sizeof(d));
for(i=1; i<=num; i++) ans = max(ans,dp(i));
printf("%d\n",ans);
}
return 0;
}