题目大意: 给你一个区间,然后给你答案 里面有奇数个1还是偶数个1.这些是一行一行的 一句话。让你判断一下到第几句话是错误的 我们可以想【a,b】 如果里面有偶数个1 就是1到a-1 和 1到b 里面的得数同为偶或者同为奇数 如果【a,b]里面有奇数个1 那么 1到a-1有奇数个1 和 1到b有偶数个1 ,或者相反。部分解释见题解 搞了好几天 看了好多代码 终于领悟一点。。。。
Description
Now and then you play the following game with your friend. Your friend writes down a sequence consisting of zeroes and ones. You choose a continuous subsequence (for example the subsequence from the third to the fifth digit inclusively) and ask him, whether this subsequence contains even or odd number of ones. Your friend answers your question and you can ask him about another subsequence and so on. Your task is to guess the entire sequence of numbers.
You suspect some of your friend's answers may not be correct and you want to convict him of falsehood. Thus you have decided to write a program to help you in this matter. The program will receive a series of your questions together with the answers you have received from your friend. The aim of this program is to find the first answer which is provably wrong, i.e. that there exists a sequence satisfying answers to all the previous questions, but no such sequence satisfies this answer.
Output
There is only one line in output containing one integer X. Number X says that there exists a sequence of zeroes and ones satisfying first X parity conditions, but there exists none satisfying X+1 conditions. If there exists a sequence of zeroes and ones satisfying all the given conditions, then number X should be the number of all the questions asked.
Sample Output
3
#include <cstdio>
#include <map>
#define maxn 5010
using namespace std;
int par[maxn],val[maxn] ;//val 存储权值
void init ()
{
for (int i=0 ; i<maxn ; i++){
par[i] = i ;
val[i] = 0 ;
}
}
int find (int x)
{
if (par[x]==x){
return x ;
}
int root = find(par[x]) ;
val[x] = (val[x]+val[par[x]])%2 ;//更新权值 ,奇数 + 偶数 余2 等于奇数 偶+ 偶。。。偶(偶数那就设为0 奇数设为1)
par[x] = root ;
return par[x] ;
}
int Union (int x,int y,int temp)
{
int root1 = find(x) ;
int root2 = find(y) ;
if (root1 == root2){ //如果两个权值都是奇数或者都是偶数 那么和取余是0 加上答案temp如果还是0 那么 这一行是对的
if ((val[x]+val[y]+temp)%2==0){
return 1 ;
}
else return 0 ;
}
else{
par[root1] = root2 ;
val[root1] = (val[x]+val[y]+temp)%2 ;
return 1 ;
}
}
int main()
{
char s[10] ;
int n,m ;
scanf("%d%d",&n,&m) ;
init() ;
map <int,int> hash ;
int i,a,b,cut=0,temp;
for (i=1 ; i<=m ; i++){
scanf("%d %d %s",&a,&b,s) ;
a-- ;
if (hash.find(a)==hash.end()) hash[a] = cut++ ;//如果没找到a,加1
int x=hash[a] ;
if (hash.find(b)==hash.end()) hash[b] = cut++ ;
int y=hash[b] ;
temp = s[0] == 'o' ?1 :0;//给出的答案 是奇数设为1 偶数设为2
if (Union(x,y,temp)==0) break ;
}
printf("%d\n",i-1) ;//找到错误 那么返回正确的行数则为 它前面几行
return 0;
}