CCF高速公路

題意:
求完強連通分量後求這寫強連通分量有多少種組合 。

這題做的有點難受。。。。。一開始沒注意到是要求 Cn2 的組合數(N的物品中取出2個有多少種組合), 以爲是求強連通分量點的總數。。。(馬德首A沒了,,,)
果然自己語文不行QAQ

下面直接貼代碼吧
模板題就不解釋了


#include <string.h>
#include <iostream>
#include <algorithm>
#include<cstdio>
using namespace std;

/*
Tarjan算法
複雜度O(N+M)
*/
/// 除了solve和主函數外才是該算法模板
const int maxn = 2e5 + 10; // 點數
const int maxm = 2e5 + 10; // 邊數

int head[maxn], tot;
int Low[maxn], DFN[maxn],Stack[maxn],Belong[maxn];//Belong數組的值是1~scc
int Index, top;
int scc;//強連通分量的個數
bool Instack[maxn];
int num[maxn];//各個強連通分量包含點的個數,數組編號1~scc
//num數組不一定需要,結合實際情況
int n ;
struct Edge
{
    int to,next;
}edge[maxn];

void addedge(int u,int v)
{
    edge[tot].to = v;edge[tot].next = head[u];head[u] = tot++;
}
void Tarjan(int u)
{
    int v;
    Low[u] = DFN[u] = ++Index;
    Stack[top++] = u;
    Instack[u] = true;
    for(int i = head[u];i != -1;i = edge[i].next)
    {
        v = edge[i].to;      // 去向
        if(!DFN[v])
        {
            Tarjan(v);
            if(Low[u] > Low[v])
                  Low[u] = Low[v];
        }
        else if(Instack[v] && Low[u] > DFN[v])
            Low[u] = DFN[v];
    }
    if(Low[u] == DFN[u])
    {
        scc++;
        do
        {
            v = Stack[--top];
            Belong[v] = scc;  // 這就是爲什麼belong【】數組裏面的值爲 1 - scc 的原因
            Instack[v] = false;
        }
        while( v!= u);
    }
}
int in[maxn],out[maxn];
int finda[100000] ;
void solve(int N)
{
    memset(DFN,0,sizeof(DFN));
    memset(Instack,false,sizeof(Instack));
    Index = scc = top = 0;
    for(int i = 1;i <= N;i++)
        if(!DFN[i]) // 如果圖有2個, 就會一把2個圖遍歷完,但通常情況下就只需要一遍
           Tarjan(i);
       //     cout << "LOW = " ;
        for(int i = 1 ; i <= N ; i++){
                finda[Belong[i]] ++ ;
        }  //   cout << endl ;
    //    cout << "BElong = " ;

        int ans = 0 ;
        for(int i = 0 ; i <= scc ; i++){
           if(finda[i]  > 1  ) ans += finda[i] * (finda[i] - 1 ) / 2 ;
        }
        cout << ans << endl ;


               return  ;
}
void init()
{
    tot = 0;
    memset(head,-1,sizeof(head));
}
int main()
{   int n , m ;
cin >> n >> m  ;
int u , v   ;
init() ;
for(int i = 0 ; i < m ; i++){
    scanf("%d%d",&u , &v) ;
    addedge(u , v) ;
}

        solve(n);

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