CF1217D Coloring Edges(思维+拓扑排序)

题目链接:http://codeforces.com/problemset/problem/1217/D

题意:
第一行给出n和m(2≤n≤5000,1≤m≤5000),代表无向图的点数和边数接下来m行,每行两个数u,v,表示一条u到v的有向边

没有自环和重边问用最少的颜色给图染色,使得任意一个环中的边没有相同的颜色,输出最少的颜色数和每条边的颜色

思路:
因为是有向图,若存在环的话,环中一定存在由小节点指向大节点的有向边和大节点指向小节点的有向边,我们把小节

点指向大节点的边染色为1,大节点指向小节点的边染色为2,这样就可以解决了,接下来判环即可,可用dfs或者拓扑

#include 
#include  
#include   
#include   
#include    
#include    
#include     
#include     
#include     
#include       
#include       
#define dll(x) scanf("%I64d",&x)
#define xll(x) printf("%I64d\n",x)
#define pii pair
#define pll pair
#define gb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define mem(X) memset((X), 0, sizeof((X)))
#define memc(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define eps 1e-6
#define gg(x) getInt(&x)
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {return b ? gcd(b, a % b) : a;}
ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
ll powmod(ll a, ll b, ll MOD) {ll ans = 1; while (b) {if (b % 2)ans = ans * a % MOD; a = a * a % MOD; b /= 2;} return ans;}
inline void getInt(int* p);
const int inf = 0x3f3f3f3f;
const int N = 5e3 + 10;

vector<int>e[N];
int n, m, du2[N], a[N], b[N], c[N];

bool tuopu()
{
	int cnt = 0;
	queue<int>Q;
	for (int i = 1; i <= n; i++)if (du2[i] == 0)Q.push(i);
	while (!Q.empty()) {
		int u = Q.front(); Q.pop(); cnt++;
		for (int v : e[u]) {
			du2[v]--;
			if (du2[v] == 0)Q.push(v);
		}
	}
	if (cnt != n)return true;
	else return false;
}

int main(int argc, char const *argv[])
{
	gb;
#ifdef ONLINE_JUDGE
#else
	freopen("D:\\test\\in.txt", "r+", stdin);
#endif
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		cin >> a[i] >> b[i];
		e[a[i]].push_back(b[i]);
		du2[b[i]]++;
	}
	if (tuopu()) {a
		cout << 2 << endl;
		for (int i = 1; i <= m; i++) {
			if (a[i] > b[i]) {
				cout << 1 << " ";
			} else {
				cout << 2 << " ";
			}
		}
	} else {
		cout << 1 << endl;
		for (int i = 1; i <= m; i++) {
			cout << 1 << " ";
		}
	}
	return 0;
}

inline void getInt(int* p) {
	char ch;
	do {
		ch = getchar();
	} while (ch == ' ' || ch == '\n');
	if (ch == '-') {
		*p = -(getchar() - '0');
		while ((ch = getchar()) >= '0' && ch <= '9') {
			*p = *p * 10 - ch + '0';
		}
	} else {
		*p = ch - '0';
		while ((ch = getchar()) >= '0' && ch <= '9') {
			*p = *p * 10 + ch - '0';
		}
	}
}

你可能感兴趣的:(codeforces)