縮點的作用
1)縮點的實際作用:把一個有向帶環圖,變成一個有向無環圖(DAG) ,這樣基於DAG的算法就能跑了。
2)可以算縮點後個點的出度
基本思想
一我們既然能在有向圖中找到環,那麼我們就可以吧環給縮成點了(利用Tarjan縮點),縮點基於一種染色實現,在DFS搜索的過程中,嘗試吧屬於同一個強連通分量的點都染成一個顏色,同一顏色的點就相當於一個點。
步驟:1)Tarjan縮點,2)染色處理,3)建有向無環圖 (DAG)
代碼:
const int MAXN = 5e3 + 20;
const int MAXM = 1e6 + 10;
int head[MAXN], cnt, tot, dfn[MAXN], low[MAXN], color[MAXN], col;
bool vis[MAXN];
int degree[MAXN];
stack<int> stc;
int n, m;
struct Edge {
int to, next, dis;
}edge[MAXM << 1];
void add_edge(int u, int v, int dis) {
edge[++cnt].to = v;
edge[cnt].next = head[u];
head[u] = cnt;
}
void Tarjan(int x) {
vis[x] = 1;
dfn[x] = low[x] = ++tot;
stc.push(x);
for(int i = head[x]; i; i = edge[i].next) {
int to = edge[i].to;
if (!dfn[to]) {
Tarjan(to);
low[x] = min(low[x], low[to]);
} else if( vis[to] ) {
low[x] = min(low[x], dfn[to]);
}
}
if(dfn[x] == low[x]) {
col ++;
while(true) {
int top = stc.top();
stc.pop();
color[top] = col; //顏色相同的點縮點
vis[top] = 0;
// cout << top << " ";
if(top == x) break;
}
//cout << endl;
}
}
void solve(){
for(int i = 1; i <= n; ++i) {
if(!dfn[i])
Tarjan(i);
}
for(int x = 1; x <= n; ++x) { //遍歷 n個節點
for(int i = head[x]; i; i = edge[i].next) { //縮點後 每個點的出度
int to = edge[i].to;
if(color[x] != color[to]) {
degree[color[x]] ++;
}
}
}
}
void init () {
cnt = 1;
tot = 0;
col = 0;
memset(vis, 0, sizeof(vis));
memset(head, 0, sizeof(head));
memset(dfn, 0, sizeof(dfn));
memset(low, 0, sizeof(low));
memset(degree, 0, sizeof(degree));
memset(color, 0, sizeof(color));
while(!stc.empty()) stc.pop();
}
int main () {
std::ios::sync_with_stdio(false);
cin.tie(0);
while(cin >> n && n) {
cin >> m;
init();
int x, y;
for(int i = 1; i <= m; ++i) {
cin >> x >> y;
add_edge(x, y, 0);
}
solve();
}
return 0;
}
練習題:
POJ-2553 (出度爲0的點)
P2002 消息擴散 (與入度連用)
P2341 [HAOI2006]受歡迎的牛 (與出度連用)
P2746 [USACO5.3]校園網Network of Schools (入度和出度)
P2863 [USACO06JAN]牛的舞會The Cow Prom (圖論知識及對強聯通的理解)
P2835 刻錄光盤 (同上)
P3387 【模板】縮點