求出 bcc 后再……根据大白书上的思路即可。
然后我用的是自定义的 stack 类模板:
#include<cstdio>
#include<cstring>
#include<vector>
//#include<stack>
#include<stdexcept>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N = ; template <typename T, size_t SIZE = N>
class stack {
T *val;
size_t tot;
size_t limit;
public:
stack(size_t limit = SIZE): limit(limit) {
val = (T*)malloc(sizeof(T) * limit);
tot = ;
}
stack(const stack<T> &s2): limit(s2.limit), tot(s2.tot) {
val = (T*)malloc(sizeof(T) * limit);
for(size_t i = ; i < tot; ++i)
val[i] = s2.val[i];
}
stack& operator = (const stack<T> &s2) {
tot = s2.tot;
limit = s2.limit;
T *temp = (T*)malloc(sizeof(T) * s2.limit);
for(size_t i = ; i < s2.tot; ++i)
temp[i] = s2.val[i];
free(val);
this->val = temp;
}
void push(const T &x) {
if(tot == limit) {
stack<T> temp(*this);
free(val);
val = (T*)malloc(sizeof(T) * (limit <<= ));
for(size_t i = ; i < temp.tot; ++i)
val[i] = temp.val[i];
}
val[tot++] = x;
}
void pop() {
if(tot == ) throw out_of_range("Stack less flow at Stack<T>::pop()");
--tot;
}
T top() const {
if(tot == ) throw out_of_range("Stack less flow at Stack<T>::top()");
return val[tot - ];
}
size_t size() const { return tot; }
bool empty() const { return tot == ; }
void clear() { tot = ; }
~stack() { free(val); }
}; struct Edge {
int u,v;
Edge(int u, int v): u(u), v(v) {}
}; vector<int> g[N], bcc[N];
int pre[N], iscut[N], bccno[N], dfs_clock, bcc_cnt;
stack<Edge, N> s; int dfs(int u, int fa) {
int lowu = pre[u] = ++dfs_clock;
int child = ;
for(int i = ; i < g[u].size(); ++i) {
int v = g[u][i];
Edge e = Edge(u,v);
if(!pre[v]) {
s.push(e);
++child;
int lowv = dfs(v,u);
lowu = min(lowu, lowv);
if(lowv >= pre[u]) {
iscut[u] = ;
++bcc_cnt;
bcc[bcc_cnt].clear();
while() {
Edge x = s.top(); s.pop();
if(bccno[x.u] != bcc_cnt) {
bccno[x.u] = bcc_cnt;
bcc[bcc_cnt].push_back(x.u);
}
if(bccno[x.v] != bcc_cnt) {
bccno[x.v] = bcc_cnt;
bcc[bcc_cnt].push_back(x.v);
}
if(x.u == u && x.v == v) break;
}
}
}
else if(pre[v] < pre[u] && v != fa) {
lowu = min(lowu, pre[v]);
s.push(e);
}
}
if(fa < && child == ) iscut[u] = ;
return lowu;
} void find_bcc(int n) {
memset(pre, , sizeof pre);
memset(iscut, , sizeof iscut);
memset(bccno, , sizeof bccno);
dfs_clock = bcc_cnt = ;
for(int i = ; i < n; ++i)
if(!pre[i]) dfs(i, -);
} int main() {
int n,x,y,Case = , maxn = ;
while(~scanf("%d",&n),n) {
for(int i = ; i <= maxn; ++i)
g[i].clear();
maxn = ;
for(int i = ; i < n; ++i) {
scanf("%d %d",&x,&y);
maxn = max(maxn, x);
maxn = max(maxn, y);
g[x].push_back(y);
g[y].push_back(x);
}
find_bcc(maxn + );
LL ans1 = , ans2 = ;
for(int i = ; i <= bcc_cnt; ++i) {
int cut = ;
for(int j = ; j < bcc[i].size(); ++j)
if(iscut[bcc[i][j]]) ++cut;
if(cut == ) {
++ans1;
ans2 *= bcc[i].size() - cut;
}
}
if(bcc_cnt == ) {
ans1 = ;
ans2 = (LL)bcc[].size() * (bcc[].size() - ) / ;
}
printf("Case %d: %lld %lld\n",++Case, ans1, ans2);
}
return ;
}