Educational Codeforces Round 72 (Rated for Div. 2) D - Coloring Edges

 题意:给一个无向图进行染色。使得不存在同色的环。问最小的颜色数并输出方案。

思路:首先 可以明确 有环的话颜色数为2,无环的话颜色数为1。

然后就是判环 ,这里总结一下有向图和无向图判环的方法。

有向图:图中存在4种边,树边,反向边,横向边和前向边。有向图中任意一个环,至少含有一条反向边。所以有向图有环的充要条件是至少含有一条反向边。

无向图:图中存在2种边,树边,反向边。无向图中的任意一个环,至少含有一条反向边。所以无向图中有环的充要条件是至少含有一条反向边。

判环之后就很简单了。无环输出1就行了。 有环就小编号的点向大编号的点连1,大编号向小编号的点连2.

#include 
using namespace std;
const int maxm = 5005;
const int maxn = 5005;
int tot=1,ver[maxm],he[maxn],ne[maxm],id[maxm],ans[maxm];
void add( int x,int y,int _id ){
    ver[++tot] = y;
    ne[tot] = he[x];
    he[x] = tot;
    id[tot] = _id;
}
int dfn[maxn],inst[maxn],cnt;
bool flag = false;
void dfs( int x ){
    dfn[x] = ++cnt;
    inst[x] = 1;
    for( int cure = he[x];cure;cure = ne[cure] ){
        int y = ver[cure];
        if(!dfn[y]){
            dfs(y);
            ans[ id[cure] ] = 1;
        }
        else{
            if( dfn[y] < dfn[x] && inst[y] ){
                flag = true;
            }
            if( dfn[y] < dfn[x] ){
                ans[ id[cure] ] = 2;
            }else{
                ans[ id[cure] ] = 1;
            }
        }
    }
    inst[x] = 0;
}
int main(){
    int n,m;
    scanf("%d%d",&n,&m);
    for( int x,y,i = 1;i<= m;i++ ){
        scanf("%d%d",&x,&y);
        add(x,y,i);
    }
    for( int i = 1;i <= n;i++ ){
        if( !dfn[i] ){
            dfs(i);
        }
    }
    if(flag){
        printf("2\n");
        for( int i = 1;i <= m;i++ ){
            printf("%d ",ans[i]);
        }
    }else{
        printf("1\n");
        for( int i = 1;i <= m;i++ ){
            printf("1 ");
        }
    }
    return 0;
}

 

你可能感兴趣的:(图论)