很容易看出这道题可以用并查集解决,但是因为长度长达10亿,而问的次数最多才5000次,所以需要离散化一下。离散化通常有两种操作,一种是需要考虑区间大小的离散。比如4对应的离散值应该小于5对应的离散值,另一种离散是随机的离散,即5对应的离散值和4对应的离散值没有大小关系,是随机的。对于这道题来说,显然是不需要考虑区间大小的离散。
这是因为对于并查集来说,每个节点都对应于一个唯一的父节点,对应的父节点和这个点的实际值是没有关系的。也就是说,对于某个区间内的1的个数来说,是该区间的大小是没有关系的。所以我们可以用map简单的离散化一下就可以了。
对于并查集来说,区间【i,j】内1的个数,我们可以表示为sum[j]-sum[i-1],这样就可以了。题目:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 4197 | Accepted: 1639 |
Description
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.
Input
Output
Sample Input
10 5 1 2 even 3 4 odd 5 6 even 1 6 even 7 10 odd
Sample Output
3ac代码:
#include <iostream>
#include <string>
#include <map>
#include <cstdio>
using namespace std;
const int N=10010;
int father[N],relation[N],k=1;
void init(){
for(int i=0;i<N;++i){
father[i]=i;
relation[i]=0;
}
}
int min(int x,int y){
return x<y?x:y;
}
int max(int x,int y){
return x>y?x:y;
}
int find(int x){
int fx=father[x];
if(x!=father[x]){
father[x]=find(father[x]);
relation[x]=(relation[fx]+relation[x])%2;
}
return father[x];
}
bool Union_Set(int x,int y,int d){
int rootx=find(x);
int rooty=find(y);
if(rootx!=rooty){
father[rooty]=rootx;
relation[rooty]=(relation[x]+d-relation[y]+2)%2;
return true;
}
else{
if((relation[x]+relation[y])%2==d)
return true;
return false;
}
}
int main(){
int len,n;
scanf("%d%d",&len,&n);
init();
map<int,int> mp;
int x,y,a,b;
string ss;
bool flag=true;
int value=n;
for(int i=1;i<=n;++i){
scanf("%d%d",&a,&b);
cin>>ss;
x=min(a,b);
y=max(a,b);
if(!flag){
continue;
}
x--;
if(mp.find(x)==mp.end()){
{mp[x]=k++;}
}
int mx=mp[x];
if(mp.find(y)==mp.end()){
{mp[y]=k++;}
}
int my=mp[y];
int d;
if(ss=="even")d=0;
else d=1;
flag=Union_Set(mx,my,d);
if(flag==false){
value=i-1;
}
}
printf("%d\n",value);
return 0;
}