【F. Graph Without Long Directed Paths】贪心

F
F. Graph Without Long Directed Paths

题意 给你n个点 m条边 保证联通 问你能否构造一张有向图(不一定联通)使得路径长度不超过2

我们很容易想到从一个点开始染色 和他相连的点染相反颜色 然后再继续递归下去染色

但是要判断一下 这个点染色和下个点染色是否相反 如果那个点已经有颜色和自己是一样的 那么肯定是NO

例如这组数据

3 3
1 2
2 3
3 1

实际上是不能染色的 因为一定会有一条2的路径 所以你把相同颜色出现的时候全局flag为false 输出NO即可

/*
    if you can't see the repay
    Why not just work step by step
    rubbish is relaxed
    to ljq
*/
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
 
#define dbg(x) cout<<#x<<" = "<< (x)<< endl
#define dbg2(x1,x2) cout<<#x1<<" = "<#define dbg3(x1,x2,x3) cout<<#x1<<" = "<#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
 
typedef pair<int,int> pll;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int _inf = 0xc0c0c0c0;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const ll _INF = 0xc0c0c0c0c0c0c0c0;
const ll mod =  (int)1e9+7;
 
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll ksm(ll a,ll b,ll mod){int ans=1;while(b){if(b&1) ans=(ans*a)%mod;a=(a*a)%mod;b>>=1;}return ans;}
ll inv2(ll a,ll mod){return ksm(a,mod-2,mod);}
const int MAX_N = 2e5+5;
int col[MAX_N],a[MAX_N],b[MAX_N];
vector<int> G[MAX_N];
bool flag;
void dfs(int x,int fa,int v)
{
    int sz = G[x].size();
    col[x] = v;
    for(int i = 0;i<sz;++i)
    {
        int to = G[x][i];
        if(to==fa) continue;
        if(col[to]==-1) dfs(to,x,1-v);
        else if(col[to] == col[x]) flag = false;
    }
    return ;
}
int main()
{
    //ios::sync_with_stdio(false);
    //freopen("a.txt","r",stdin);
    //freopen("b.txt","w",stdout);
    int n,m;
    flag = true;
    scanf("%d%d",&n,&m);
    memset(col,-1,sizeof(col));
    for(int i = 1;i<=m;++i)
    {
        scanf("%d%d",&a[i],&b[i]);
        G[a[i]].push_back(b[i]);
        G[b[i]].push_back(a[i]);
    }
    dfs(1,-1,0);
    if(!flag)
    {
        printf("NO\n");
        return 0;
    }
    printf("YES\n");
    for(int i = 1;i<=m;++i)
    {
        if(col[a[i]]==1) printf("1");
        else printf("0");
    }
    //fclose(stdin);
    //fclose(stdout);
    //cout << "time: " << (long long)clock() * 1000 / CLOCKS_PER_SEC << " ms" << endl;
    return 0;
}
 
 

你可能感兴趣的:(ACM,Codeforces,贪心)