竹園論壇

標題: [ 問效率 ] TOJ - 143 [打印本頁]

作者: jd3    時間: 2014-9-28 00:57
標題: [ 問效率 ] TOJ - 143
本帖最後由 jd3 於 2014-9-28 20:02 編輯

為什麼用union-find會比dfs下去分快?
是我的常數太大嗎...


TLE CODE
[C++] 純文本查看 復制代碼
#include<iostream>
#include<cstdio>
#include<vector>

using namespace std;

vector<int> list[100010];
int color[100010];

bool dfs(int node)
{
    for(int i = 0 ; i < list[node].size() ; i++)
    {
        int next_node = list[node];
        if(color[next_node] == color[node])
            return false;
        else if(color[next_node] == -1)
        {
            color[next_node] = 1-color[node];
            if(dfs(next_node) == false)
                return false;
        }
    }
    return true;
}

int main()
{
    int n,m;
    int a,b;
    while(~scanf("%d%d",&n,&m))
    {
        for(int i = 0 ; i < n ; i++)
        {
            color = -1;
            list.clear();
        }
        
        
        for(int i = 0 ; i < m ; i++)
        {
            scanf("%d%d",&a,&b);
            list[a].push_back(b);
            list.push_back(a);
        }
        
        bool yes = true;
        for(int i = 0 ; i < n ; i++)
        {
            if(color == -1)
            {
            //    cout << "start : " << i << endl;
                color = 1;
                if(!dfs(0))
                {
                    yes = false;
                    break;
                }
            }
        }
        
        if(yes)
            puts("YES");
        else
            puts("NO");
    }
   
    return 0;
}







作者: Sylveon    時間: 2014-9-28 10:32
DFS : O( E+V )
Union-Find 平均使用的話可以達到均攤O(1),總共為O(E)

但是Union-Find的常數 << DFS+遞迴的常數,光看code長度就可以看的出來




歡迎光臨 竹園論壇 (http://forum.tfcis.org/) Powered by Discuz! X3.2