1093: [ZJOI2007]最大半连通子图
Time Limit: 30 Sec Memory Limit: 162 MB
Description
一个有向图G=(V,E)称为半连通的(Semi-Connected),如果满足:?u,v∈V,满足u→v或v→u,即对于图中任意
两点u,v,存在一条u到v的有向路径或者从v到u的有向路径。若G’=(V’,E’)满足V’?V,E’是E中所有跟V’有关的边,
则称G’是G的一个导出子图。若G’是G的导出子图,且G’半连通,则称G’为G的半连通子图。若G’是G所有半连通子图
中包含节点数最多的,则称G’是G的最大半连通子图。给定一个有向图G,请求出G的最大半连通子图拥有的节点数K
,以及不同的最大半连通子图的数目C。由于C可能比较大,仅要求输出C对X的余数。
Input
第一行包含两个整数N,M,X。N,M分别表示图G的点数与边数,X的意义如上文所述接下来M行,每行两个正整
数a, b,表示一条有向边(a, b)。图中的每个点将编号为1,2,3…N,保证输入中同一个(a,b)不会出现两次。N ≤1
00000, M ≤1000000;对于100%的数据, X ≤10^8
Output
应包含两行,第一行包含一个整数K。第二行包含整数C Mod X.
Sample Input
6 6 20070603
1 2
2 1
1 3
2 4
5 6
6 4
Sample Output
3
3
思路:
我们发现强连通分量一定是满足这个条件的。那么如果不去考虑强连通分量呢?
那么剩下的点之间一定是不能互相到达的,其中的半连通分量就是强连通分量缩点后的一条链。
问题就成为求缩点后的图里的最长链。
然后就拓扑排序,dp的维护最长链与对应子图个数。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
using namespace std;
const int N = 100005, M = 1000005;
int idx=0, idc=1, n, m, cnt=0, MOD;
int head[N], e[M<<1];
int dfn[N], low[N], place[N], wgh[N];
int in[N], vis[N], f[N], num[N];
vector<int> G[N];
bool ins[N];
stack <int> state;
struct Edge{
int to, next;
}ed[M<<1];
void adde(int u, int v) {
ed[++idc].to = v;
ed[idc].next = head[u];
head[u] = idc;
}
void tarjan(int u){
dfn[u] = low[u] = ++idx;
vis[u] = ins[u] = 1;
state.push(u);
for(int i=head[u]; i; i=ed[i].next){
int v = ed[i].to;
if( !vis[v] ){
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if( ins[v] ){
low[u] = min(low[u], dfn[v]);
}
}
if(dfn[u] == low[u]){
cnt++; int t=-1;
while(t != u){
t = state.top();
place[t] = cnt;
ins[t] = 0;
wgh[cnt]++;//记录每个强连通分量中包含的点的个数
state.pop();
}
}
}
void rebuild () {//重新构图
for(int x=1; x<=n; x++)
for(int k=head[x]; k; k=ed[k].next){
int v = ed[k].to;
if(place[x] != place[v])
G[place[x]].push_back(place[v]), ++in[place[v]];//统计入度
}
}
void dp () {
queue<int> q;
for(int i=1; i<=cnt; i++) {
if( !in[i] ) q.push(i);
f[i] = wgh[i]; num[i] = 1;
}//按照拓扑序跑
while( !q.empty() ){
int now=q.front(); int v; q.pop();
for(int i=0; i<G[now].size(); i++) {
in[v = G[now][i]]--;
if( !in[v] ) q.push(v);
if( vis[v] == now ) continue;//新图可能有重边。
if(f[now] + wgh[v] > f[v]) {//更改最长链
f[v] = f[now] + wgh[v];
num[v] = num[now];//满足条件的图的数量
}
else if(f[now] + wgh[v] == f[v])
num[v] = (num[v] + num[now]) % MOD;//经过到v的链长,与之前经过其它点到达的链长一样,更改数量
vis[v] = now;
}
}
}
int main () {
int u, v;
scanf("%d%d%d", &n, &m, &MOD);
for(int i=1; i<=m; i++) {
scanf("%d%d", &u, &v);
adde(u, v);
}
for(int i=1; i<=n; i++)
if( !dfn[i] ) tarjan(i);//缩点
rebuild();
dp();
int maxx = 0, ans = 0;
for(int i=1; i<=cnt; i++){
if(f[i] > maxx) maxx = f[i], ans = num[i];
else if(f[i] == maxx) ans = (ans + num[i]) % MOD;
}
printf("%d\n%d\n", maxx, ans);
return 0;
}