Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

这道题大家写麻烦了! tarjan+缩点就做完了啊~拓扑排序干嘛 0_0【329ms】

Posted by ssdut_201392326 at 2014-08-12 16:13:54 on Problem 2762
就是先tarjan+缩点 (hh神的模板)
然后新图必须满足:
1.入度为0的点只能有一个
2.出度为0的点只能有一个
入度在构建新图时顺便开个数组记录一下就行了

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int maxm = 10000;

vector <int> edge[maxm];
vector <int> now[maxm];
int hash[maxm];
bool vis[maxm];
int dfn[maxm],Index;
int low[maxm];
int idx[maxm];
int ss[maxm],top;
bool InStack[maxm];
bool ruInNew[maxm];
int n;
int nn;

void dfs(int u)
{
    vis[u] = true;
    dfn[u] = low[u] = Index++;
    InStack[u] = true;
    ss[++top] = u;
    for(int i=0;i<edge[u].size();i++)
    {
        int v = edge[u][i];
        if(!vis[v]){
            dfs(v);
            low[u] = min(low[u],low[v]);
        }
        else if(InStack[v])
            low[u] = min(low[u],dfn[v]);
    }
    if(low[u] == dfn[u])
    {
        int v = -1;
        nn++;
        while(u != v)
        {
            v = ss[top--];
            InStack[v] = false;
            idx[v] = nn;
        }
    }
}

void tarjan()
{
    int i;
    for(i=0;i<maxm;i++) now[i].clear();
    memset(vis,0,sizeof(vis));
    memset(ruInNew,0,sizeof(ruInNew));
    Index = 1;
    top = 0;
    nn = 0;
    for(i=1;i<=n;i++){
        if(!vis[i]) dfs(i);
    }
    memset(hash,-1,sizeof(hash));
    for(i=1;i<=n;i++)
        for(int j=0;j<edge[i].size();j++)
        {
            int v = edge[i][j];
            if(idx[i] != idx[v] && hash[idx[i]] != idx[v])
            {
                hash[idx[i]] != idx[v];
                now[idx[i]].push_back(idx[v]);
                ruInNew[v] = true;
            }
        }
}

int ok()
{
    int i;
    int ru=0, chu=0;
    for(i=1;i<=nn;i++)
    {
        if(ruInNew[i] == false) ru++;
        if(now[i].size() == 0) chu++;
    }
    if(ru==1 && chu==1) return 1;
    return 0;
}

int main()
{
    //freopen("input.txt","r",stdin);
    int T,i,m;
    scanf("%d",&T);
    while(T--)
    {
        for(i=0;i<maxm;i++) edge[i].clear();
        scanf("%d%d",&n,&m);
        while(m--)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            edge[u].push_back(v);
        }
        tarjan();
        if(ok()) cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator