Problem
acm.hdu.edu.cn/showproblem.php?pid=6109
Meaning
给出若干个条件:
xi=xj
或
xi≠xj
,它们分属若干组,但组与组之间的分隔符没了,要重新分隔这几组条件。
每一组条件的特点是:不可能成立,但去掉最后一个条件后,就可以成立。
Analysis
每次都贪心地常试将尽量多的条件放进当前这组,遇到第一个与已有条件冲突时,就是分隔的时候。
相等有传递性,用并查集维护;不等没有传递性,用 set 维护。
注意到:若
x1=x2,x1≠x3,x2≠x4
,那么有:
x1≠x4,x2≠x3
。所以在用并查集将
x1、x2
合并时(比如将
x1
合并到
x2
),就要将
x1
的不相等的信息合并到
x2
上。
Code
#include <cstdio>
#include <set>
using namespace std;
const int N = 100000;
set<int> st[N+1];
int fa[N+1], rk[N+1];
void clear(int n)
{
for(int i = 1; i <= n; ++i)
{
rk[i] = 1;
fa[i] = i;
st[i].clear();
}
}
void pushup(int x, int y)
{
for(set<int>::iterator it = st[x].begin(); it != st[x].end(); ++it)
st[y].insert(*it);
}
int root(int x)
{
if(x == fa[x])
return x;
pushup(x, fa[x]); // 儿子信息合并到父亲
return fa[x] = root(fa[x]);
}
void unite(int x, int y)
{
int rx = root(x), ry = root(y);
if(rk[rx] < rk[ry])
fa[rx] = ry;
else
{
fa[ry] = rx;
if(rk[rx] == rk[ry])
++rk[rx];
}
}
int ans[N];
int main()
{
int L;
scanf("%d", &L);
clear(L);
int top = 0;
for(int i = 0, x, y, e, cnt = 0; i < L; ++i)
{
scanf("%d%d%d", &x, &y, &e);
++cnt;
x = root(x);
y = root(y);
if(e)
{
if(x == y)
continue;
if(st[x].count(y) || st[y].count(x))
{
ans[top++] = cnt;
cnt = 0;
clear(L);
}
else
unite(x, y);
}
else
{
if(x == y)
{
ans[top++] = cnt;
cnt = 0;
clear(L);
}
else
{
st[x].insert(y);
st[y].insert(x);
}
}
}
printf("%d\n", top);
for(int i = 0; i < top; ++i)
printf("%d\n", ans[i]);
return 0;
}