题目:
http://www.lightoj.com/volume_showproblem.php?problem=1251
题意:
有m个候选人,有n个选民,每个选民投票时有两个选择,问能不能满足所有选民的至少一个选择,如果可以,输出当选的人,多解输出任意一组
思路:
此题中两个选择是或的关系,简单题
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std;
const int N = 20010, INF = 0x3f3f3f3f;
const double eps = 1e-8;
struct edge
{
int to, next;
} g[N*10], g1[N*10];
int cnt, head[N], cnt1, head1[N];
int dfn[N], low[N], scc[N], st[N], top, num, idx;
int pos[N], color[N], indeg[N];
bool vis[N];
int n, m, cas;
void add_edge(int v, int u)
{
//printf("%d %d\n", v, u);
g[cnt].to = u, g[cnt].next = head[v], head[v] = cnt++;
}
void add_edge1(int v, int u)
{
g1[cnt1].to = u, g1[cnt1].next = head1[v], head1[v] = cnt1++;
}
void init()
{
memset(head, -1, sizeof head);
memset(dfn, -1, sizeof dfn);
memset(vis, 0, sizeof vis);
top = num = idx = cnt = 0;
}
void tarjan(int v)
{
dfn[v] = low[v] = ++idx;
vis[v] = true, st[top++] = v;
int u;
for(int i = head[v]; i != -1; i = g[i].next)
{
u = g[i].to;
if(dfn[u] == -1)
{
tarjan(u);
low[v] = min(low[v], low[u]);
}
else if(vis[u]) low[v] = min(low[v], dfn[u]);
}
if(dfn[v] == low[v])
{
num++;
do
{
u = st[--top], vis[u] = false, scc[u] = num;
}
while(u != v);
}
}
void toposort()
{
queue<int> que;
for(int i = 1; i <= num; i++)
if(indeg[i] == 0) que.push(i);
while(! que.empty())
{
int v = que.front(); que.pop();
if(color[v] == 0) color[v] = 1, color[pos[v]] = 2;
for(int i = head1[v]; i != -1; i = g1[i].next)
{
int u = g1[i].to;
if(--indeg[u] == 0) que.push(u);
}
}
}
bool solve()
{
for(int i = 1; i <= 2 * n; i++)
if(dfn[i] == -1) tarjan(i);
for(int i = 1; i <= n; i++)
{
if(scc[i] == scc[i+n]) return false;
pos[scc[i]] = scc[i+n], pos[scc[i+n]] = scc[i];
}
cnt1 = 0;
memset(head1, -1, sizeof head1);
memset(indeg, 0, sizeof indeg);
memset(color, 0, sizeof color);
for(int i = 1; i <= 2 * n; i++)
for(int j = head[i]; j != -1; j = g[j].next)
if(scc[i] != scc[g[j].to])
add_edge1(scc[g[j].to], scc[i]), indeg[scc[i]]++;
toposort();
return true;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
init();
scanf("%d%d", &m, &n);
for(int i = 1; i <= m; i++)
{
int a, b;
scanf("%d%d", &a, &b);
if(a > 0 && b > 0) add_edge(a + n, b), add_edge(b + n, a);
else if(a > 0 && b < 0) add_edge(a + n, -b + n), add_edge(-b, a);
else if(a < 0 && b > 0) add_edge(-a, b), add_edge(b + n, -a + n);
else add_edge(-a, -b + n), add_edge(-b, -a + n);
}
if(solve())
{
int tot = 0, ans[N];
for(int i = 1; i <= n; i++)
if(color[scc[i]] == 1) ans[++tot] = i;
printf("Case %d: Yes\n", ++cas);
printf("%d", tot);
for(int i = 1; i <= tot; i++) printf(" %d", ans[i]);
printf("\n");
}
else printf("Case %d: No\n", ++cas);
}
return 0;
}