UVA-The Largest Clique 11324

最大團,

problem:給一個有向圖G, 求一個節點數最大的點集, 使得該點集中的任意兩個節點至少要有一條路徑

->

那麼可知, G中的SCC要麼都選, 要麼都不選(不選是因爲這是有向圖選了之後的無法納入範圍), 那麼問題就簡單了

將每個SCC縮成一個點, 變成在DAG上DP

->

code:

#include <stack>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

#define N 50005
#define next Next
#define begin Begin
#define mem(a) memset(a, 0, sizeof(a))
#define rep(i, j, k) for(int i=j; i<=k; ++i)
#define erep(i, u) for(int i=begin[u]; i; i=next[i])
void read(int &x){
	char c=getchar();x=0;while(c<'0' || c>'9')c=getchar();
	while(c>='0' && c<='9')x=x*10+c-'0', c=getchar();
}

int begin[N<<1], to[N<<1], next[N<<1], e;
void add(int x, int y){
	to[++e]=y;
	next[e]=begin[x];
	begin[x]=e;
}
int n, m, low[N], pre[N], sccid[N], scc_cnt, clock_;
stack<int>s;
void dfs(int u){
	pre[u]=low[u]=++clock_;
	s.push(u);
	erep(i, u){
		int v=to[i];
		if(!pre[v])dfs(v),low[u]=min(low[u], low[v]);
		else if(!sccid[v])low[u]=min(low[u], pre[v]);
		//notice! array low can only reach the point which is in the same SCC;   
	}
	if(pre[u] == low[u]){
		scc_cnt++;
		while(1){
			int x=s.top();s.pop();
			sccid[x]=scc_cnt;if(x == u)break;
		}
	}
}
void solve(){
	clock_ = scc_cnt = 0;
	mem(pre);mem(sccid);
	rep(i, 1, n)
		if(!pre[i])
			dfs(i);
}

int f[1005], w[1005];
bool p[1005],vis[1005][1005];
int dp(int u){
	if(f[u]>=0)return f[u];
	f[u]=w[u];
	rep(v, 1, scc_cnt)
		if(v!=u && vis[u][v])f[u]=max(f[u], w[u]+dp(v));
	return f[u];
}
int main(){
#ifndef ONLINE_JUDGE
	freopen("data.in", "r", stdin);
	freopen("result.out", "w", stdout);
#endif
	int _;
	read(_);
	while(_--){
		e=0;
		mem(begin);
		memset(f, -1, sizeof(f));
		mem(vis);mem(w);
		read(n);read(m);
		rep(i, 1, m){
			int u, v;
			read(u);read(v);
			add(u, v);
		}
		solve();
		rep(i, 1, n){
			w[sccid[i]]++;
			erep(j, i)
				vis[sccid[i]][sccid[to[j]]]=true;
		}
		int res=0;
		rep(i, 1, scc_cnt)
			res=max(res, dp(i));
		printf("%d\n", res);
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章