本题大致就是设虚拟源点 带权并查集,设 为虚拟源点,代表已知值的集合。
对于 的第一种操作:由于当一个集合里任意知道一个元素的值可以通过 推断出根节点的值再由根节点推断出集合内所有元素的值,所以应该将该点集合内所有元素全部合到 节点上。
对应合并时权值的修改可以自己举几个例子找一下规律,类比一下经典带权并查集其实并不难找。
以下附上代码希望可以帮助到大家。
//UVA12232 Exclusive-OR。
//血的教训:t 和 root 里一开始的 t 重复了,调了一个小时才发现,改 temp 后就过了。
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const ll inf = 2e18;
const int N=2e4+10,P=1e9+7;
int pre[N],t,dis[N],out;//pre 记录父亲,dis 记录点与根节点值的异或值。
//out是当发现冲突时用于跳出除读入外操作的标记。
int root(int x)
{
if(pre[x] == x)return x;
int temp = pre[x];
pre[x] = root(temp);//先递归更新父亲的 dis 的值。
dis[x] ^= dis[temp];//再回溯更新 x 的 dis 值可以通过画图得出这个规律。
return pre[x];
}
int read(string &s,int &a,int &b,int &c)
{
getline(cin,s);
return sscanf(s.c_str(),"%d %d %d",&a,&b,&c);//通过 sscanf 的返回值来处理题目的输入
}
void init(int n)
{
out = 0;
cout << "Case " << ++ t << ":\n";
for(int i = 0;i <= n;++ i)pre[i] = i,dis[i] = 0;
}
int merge(int x,int y,int v,int n)
{
int xr = root(x),yr = root(y);
if(xr == yr)return (v == (dis[x] ^ dis[y]));
if(xr == n)swap(xr,yr);//设n号节点为虚拟源点,意指已经推断出值的点的集合
pre[xr] = yr;
dis[xr] = dis[x] ^ dis[y] ^ v;
return 1;
}
void query(int k,int n)
{
int res = 0;
map<int,int>mp;
//使用map记录各个非n的根节点的数量当某个根的数为偶数时计算的时候就会被约去,此时这个根的值不会影响结果
mp.clear();
for(int i = 1;i <= k;++ i)
{
int x;cin >> x;
if(out)continue;
int xr = root(x);
if(xr != n)++ mp[xr];
res ^= dis[x];
}
if(out)return;
for(auto x : mp)
{
if(x.second & 1)//当某个根的数为奇数时那么它的值会影响结果且该根不在n节点上所以我们无从知晓res。
{
cout << "I don't know.\n";
return;
}
}
cout << res << "\n";
}
void solve()
{
int n,q;cin >> n >> q;
if(n == 0 && q == 0)return;
init(n);
int cnt = 0;//记录有几条声明。
while(q --)
{
char op;cin >> op;
if(op == 'I')
{
++ cnt;
string s;
int a,b,c;
int _ = read(s,a,b,c);//通过read的返回值确定I的操作类型。
if(out)continue;
int fg;
if(_ == 2) fg = merge(a,n,b,n);
//因为当一个集合里任意知道一个元素的值可以通过dis推断出根节点的值再由根节点推断出集合内所有元素的值,
//所以应该将该点集合内所有元素全部合到 n 节点上。
else fg = merge(a,b,c,n);
if(!fg)out = cnt;
}else {
int k;cin >> k;
query(k,n);
}
}
if(out)cout << "The first " << out << " facts are conflicting.\n";
cout << "\n";
solve();
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int _ = 1;
//cin >> _;
while(_--)solve();
return 0;
}
/*
提供一组数据希望对你有一些帮助。
6 10
I 5 2
Q 2 2 2
I 1 1
I 1 2 3
I 3 1
Q 1 2
Q 2 3 2
I 3 4 5
I 4 5 6
Q 2 1 5
0 0
*/