题目:
给你一个图(邻接表形式),让你给每个点染色,共有三种颜色1,2,3,相邻的两个点的颜色的差值要等于1(1可以和2连,2可以和3连,1不能和3连),要求最后有n1个1,n2个2,n3个3,问你能不能染出来,如果不能输出NO,可以就输出任意一种染色方案。
输入1
6 3 //6个点3条边
2 2 2 //n1 n2 n3
3 1
5 4
2 5
输出1
YES
112323
输入2
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
输出2
NO
思路,实际上1和3是等效的。相当于一个点要么是2,要么是1 3,这样处理然后就可以强连通分量分解,然后给这个强连通分量染色。问题就抽象成了这样,
有t个物品,每个物品有u价值和v价值,同时你可以选择将物品的u价值和v价值可以互换(swap(u,v)),对于每种物品,你都可以选择换或者不换。su = u价值的和,sv等于v价值的和。
然后看能不能su等于n2,或者sv=n2,
这道题实际上跟这道题一模一样
https://blog.youkuaiyun.com/Fawkess/article/details/104864678
然后是代码
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <stack>
#define INF 0x3f3f3f3f
#define IMAX 2147483646
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define uint unsigned int
using namespace std;
int n, m;
int n1, n2, n3;
vector<int> e[5003];
int tot, sum[5003][2], f[5003], c[5003];
int dp[5003][5003], ans[5003];
bool flag, v[5003];
void dfs(int x){
v[x] = true, f[x] = tot;
++sum[tot][c[x]];
for (int i = 0; i < e[x].size(); i++) {
int to = e[x][i];
if (!v[to])
c[to] = (c[x] ^ 1), dfs(to);
else if (c[to] == c[x]) {
flag = true; return;
}
}
}
void solve(int k, int x){
if (x == 0) return;
if (dp[x - 1][k - sum[x][0]])
ans[x] = 0, solve(k - sum[x][0], x - 1);
else
ans[x] = 1, solve(k - sum[x][1], x - 1);
}
int main() {
scanf("%d%d", &n, &m);
scanf("%d%d%d", &n1, &n2, &n3);
for (int i = 1,v,u; i <= m; i++) {
scanf("%d%d", &u, &v);
e[u].push_back(v), e[v].push_back(u);
}
dp[0][0] = 1;
for (int i = 1; i <= n; i++)
if (!v[i]){
++tot;
c[i] = 0, sum[tot][0] = sum[tot][1] = 0;
dfs(i);
if (flag) {
puts("NO");
return 0;
}
for (int j = n; j >= sum[tot][0]; j--)
dp[tot][j] |= dp[tot - 1][j - sum[tot][0]];
for (int j = n; j >= sum[tot][1]; j--)
dp[tot][j] |= dp[tot - 1][j - sum[tot][1]];
}
if (dp[tot][n2] == 0) {
puts("NO");
return 0;
}
solve(n2, tot);
for (int i = 1; i <= n; i++)
if (c[i] == ans[f[i]])
c[i] = 2;
else if (n3)
c[i] = 3, --n3;
else
c[i] = 1;
puts("YES");
for (int i = 1; i <= n; i++)
printf("%d", c[i]);
return 0;
}