Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 4587 | Accepted: 1799 |
Description
Input
Output
Sample Input
10 5 1 2 even 3 4 odd 5 6 even 1 6 even 7 10 odd
Sample Output
3
Source
//脑袋不好使呀,经验不足
#include <iostream> #include <stdio.h> #include <string.h> #include <algorithm> #include <queue> #include <cmath> #define N 5677 using namespace std; struct node { int val,next; }ed[N]; int h[N]; int f[N],s[N]; int Find(int x) { if(x!=f[x]) { int tp=Find(f[x]); s[x]^=s[f[x]];//想了一下午才明白为什么这样是对的,因为压缩路径后都直接连到根了,不会再有2次 return f[x]=tp; } return x; } int cnt; int hash(int n) { int e,m=n%N; for(e=h[m];e!=-1;e=ed[e].next) { if(ed[e].val==n) return e; if(ed[e].next==-1) break; } ed[cnt].val=n; ed[cnt].next=h[m]; h[m]=cnt++; return cnt-1; } int xo; bool un(int x,int y) { int rx=Find(x); int ry=Find(y); if(rx!=ry) { f[ry]=rx; s[ry]=s[x]^s[y]^xo; return false; } return true; } int main() { // freopen("in.txt","r",stdin); int i,n; int len; char op[6]; memset(h,-1,sizeof(h)); int from,to; for(i=0;i<=N;i++) f[i]=i; scanf("%d",&len); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d %d %s",&from,&to,op); xo=0; if(op[0]=='o') xo=1; from=hash(from-1); to=hash(to); if(un(from,to)) { if((s[from]^s[to])!=xo) { break; } } } printf("%d\n",i); return 0; }
//以下是在 http://acm.timus.ru/problemset.aspx
http://acm.timus.ru/problem.aspx?space=1&num=1003
Ac的代码
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
#define N 5377
#define M 10002
struct node
{
int val;
int next;
}E[N];
int v[N];
int cnt;
int hsh(int n)//这里不能写hash,会和STL里面hash重到
{
int k=n%N;
for(int e=v[k];e!=-1;e=E[e].next)
{
if(E[e].val==n)
return e;
}
E[cnt].next=v[k];
E[cnt].val=n;
v[k]=cnt++;
return cnt-1;
}
int F[M],r[M];
int Find(int x)
{
if(x!=F[x])
{
int pf=F[x];
F[x]=Find(F[x]);
r[x]=r[x]^r[pf];
return F[x];
}
return x;
}
int main()
{
int len,q;
int a,b;
int i,Xor;
char op[6];
while(scanf("%d",&len),len!=-1)
{
scanf("%d",&q);
cnt=0;
int t=q<<1;
for(i=0;i<t;i++)
F[i]=i,r[i]=0;
memset(v,-1,sizeof(v));
for(i=0;i<q;i++)
{
scanf("%d %d %s",&a,&b,op);
a=hsh(a-1);
b=hsh(b);
Xor=0;
if(op[0]=='o')
Xor=1;
int x=Find(a);
int y=Find(b);
if(x==y)
{
if((r[a]^r[b])!=Xor)
break;
}
else
{
F[y]=x;
r[y]=r[a]^r[b]^Xor;
}
}
printf("%d\n",i);
if(i<q) i++;
for(;i<q;i++)
scanf("%d %d %s",&a,&b,op);
}
return 0;
}