传送门
文章目录
- 题意:
- 思路:
题意:
给你一张图,你需要给这个图的边染色,保证如果有环那么这个环内边的颜色不全相同,输出染色方案和用的颜色个数。
n,m≤5e3n,m\le5e3n,m≤5e3
思路:
经过分析不难发现,我们最多用两种颜色,如果要用两种颜色当且仅当这个图存在环,否则一种颜色即可。
我们可以直接跑一个dfsdfsdfs树,让后再上面判环,如果是非树边再看一下是否再dfsdfsdfs树上,在的话就构成环,染成222颜色即可。否则就染为111。
还可以直接根据拓扑来判断环,如果有环那么u<vu<vu<v的时候染111,u>vu>vu>v的时候染222即可,可以证明一个环内的ididid肯定不是严格递增,所以一定会有两种不同颜色。
// Problem: D. Coloring Edges
// Contest: Codeforces - Educational Codeforces Round 72 (Rated for Div. 2)
// URL: https://codeforces.com/contest/1217/problem/D
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")
//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#include<random>
#include<cassert>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid ((tr[u].l+tr[u].r)>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;const int N=1000010,M=N*2,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;int n,m;
vector<PII>v[N];
int col[N],d[N],dfn[N],idx;
bool flag;void dfs(int u,int st) {dfn[u]=1;for(auto x:v[u]) {if(dfn[x.X]==0) col[x.Y]=1,dfs(x.X,u);else if(dfn[x.X]==2) col[x.Y]=1;else col[x.Y]=2,flag=true;}dfn[u]=2;
}int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0); scanf("%d%d",&n,&m);for(int i=1;i<=m;i++) {int a,b; scanf("%d%d",&a,&b);v[a].pb({b,i}); }for(int i=1;i<=n;i++) if(!dfn[i]) {dfs(i,0);} if(flag) puts("2");else puts("1");for(int i=1;i<=m;i++) printf("%d ",col[i]);puts("");return 0;
}
/**/