1. 程式人生 > >HDU1269迷宮城堡------------------用Tarjan演算法計算強連通分量

HDU1269迷宮城堡------------------用Tarjan演算法計算強連通分量

Problem Description 
為了訓練小希的方向感,Gardon建立了一座大城堡,裡面有N個房間(N<=10000)和M條通道(M<=100000),每個通道都是單向的,就是說若稱某通道連通了A房間和B房間,只說明可以通過這個通道由A房間到達B房間,但並不說明通過它可以由B房間到達A房間。Gardon需要請你寫個程式確認一下是否任意兩個房間都是相互連通的,即:對於任意的i和j,至少存在一條路徑可以從房間i到房間j,也存在一條路徑可以從房間j到房間i。

Input 
輸入包含多組資料,輸入的第一行有兩個數:N和M,接下來的M行每行有兩個數a和b,表示了一條通道可以從A房間來到B房間。檔案最後以兩個0結束。

Output 
對於輸入的每組資料,如果任意兩個房間都是相互連線的,輸出”Yes”,否則輸出”No”。

Sample Input 
3 3 
1 2 
2 3 
3 1 
3 3 
1 2 
2 3 
3 2 
0 0

Sample Output 
Yes 
No

今天別人問了我這個問題,百度了一下Tarjan演算法,花了一個多小時,果然自己還是太菜了,還得不斷學習,加油!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10000
typedef struct{
  int m,n;
}node;
typedef struct{
  int begin,end;
}path;
typedef struct node_s{                     //構建鄰接表的資料結構
  int adjvex;
  struct node_s* next;
}Enode;
typedef struct{
  int vertex;
  Enode* FirstEdge;
}Vnode;
int visit[N];

void init(Vnode *all,int n,int m,path *map)                //將輸入的資料構造為鄰接表
{
    int i;
    Enode* temp;

    for(i=1;i<=n;i++)
    {
        all[i].vertex=i;
        all[i].FirstEdge=NULL;
    }
    for(i=0;i<m;i++)
    {
        temp=(Enode*)malloc(sizeof(Enode));
        temp->adjvex=map[i].end;
        temp->next=all[map[i].begin].FirstEdge;
        all[map[i].begin].FirstEdge=temp;
    }
}

void dfs(Vnode *all,int n,int *temp)                    //DFS查詢結點n的子樹中的結點的最小值
{
    Enode *p=all[n].FirstEdge;
    visit[n]=1;
    while(p)
    {
        if(p->adjvex<*temp)
            *temp=p->adjvex;
        if(!visit[p->adjvex])
            dfs(all,p->adjvex,temp);
        p=p->next;
    }
}

void min(Vnode *all,int n,int *LOW)                          //修改LOW[n]
{
    Enode *p=all[n].FirstEdge;
    int temp=10000,index=LOW[n];

    while(p)
    {
        memset(visit,0,sizeof(visit));
        dfs(all,p->adjvex,&temp);
        if(temp<index)
            index=temp;
        p=p->next;
    }
    LOW[n]=index;
}

int tarjan(int *DFS,int *LOW,int n,Vnode *all)                       //返回圖中強連通分量的個數
{
    int count=0,i;

    for(i=1;i<=n;i++)
    {
        DFS[i]=i;
        LOW[i]=i;
    }
    for(i=1;i<=n;i++)
        min(all,i,LOW);
    for(i=1;i<=n;i++)
        if(LOW[i]==DFS[i])
            count++;

    return count;
}

int main()
{
    node one;
    path *map;
    Vnode *all;
    int *DFS,*LOW;
    int i,flag;

    scanf("%d%d",&(one.n),&(one.m));
    map=(path*)malloc(one.m*sizeof(path));

    for(i=0;i<one.m;i++)
        scanf("%d%d",&(map[i].begin),&(map[i].end));

    all=(Vnode*)malloc((one.n+1)*sizeof(Vnode));
    DFS=(int*)malloc((one.n+1)*sizeof(int));
    LOW=(int*)malloc((one.n+1)*sizeof(int));
    init(all,one.n,one.m,map);

    if((flag=tarjan(DFS,LOW,one.n,all))==1)
        printf("\nYes\n");
    else
        printf("\nNo\n");

    return 0;
}

注意!上述程式碼與AC格式是不符,只需要稍加修改即可!