题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1149

水题。。。。。
直接BFS。
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<fstream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<utility>
#include<set>
#include<bitset>
#include<vector>
#include<functional>
#include<deque>
#include<cctype>
#include<climits>
#include<complex>
//#include<bits/stdc++.h>适用于CF,UOJ,但不适用于poj using namespace std; typedef long long LL;
typedef double DB;
typedef pair<int,int> PII;
typedef complex<DB> CP; #define mmst(a,v) memset(a,v,sizeof(a))
#define mmcy(a,b) memcpy(a,b,sizeof(a))
#define re(i,a,b) for(i=a;i<=b;i++)
#define red(i,a,b) for(i=a;i>=b;i--)
#define fi first
#define se second
#define m_p(a,b) make_pair(a,b)
#define SF scanf
#define PF printf
#define two(k) (1<<(k)) template<class T>inline T sqr(T x){return x*x;}
template<class T>inline void upmin(T &t,T tmp){if(t>tmp)t=tmp;}
template<class T>inline void upmax(T &t,T tmp){if(t<tmp)t=tmp;} const DB EPS=1e-;
inline int sgn(DB x){if(abs(x)<EPS)return ;return(x>)?:-;}
const DB Pi=acos(-1.0); inline int gint()
{
int res=;bool neg=;char z;
for(z=getchar();z!=EOF && z!='-' && !isdigit(z);z=getchar());
if(z==EOF)return ;
if(z=='-'){neg=;z=getchar();}
for(;z!=EOF && isdigit(z);res=res*+z-'',z=getchar());
return (neg)?-res:res;
}
inline LL gll()
{
LL res=;bool neg=;char z;
for(z=getchar();z!=EOF && z!='-' && !isdigit(z);z=getchar());
if(z==EOF)return ;
if(z=='-'){neg=;z=getchar();}
for(;z!=EOF && isdigit(z);res=res*+z-'',z=getchar());
return (neg)?-res:res;
} const int maxN=; int N;
PII a[maxN+];
int maxdep,dep[maxN+];
int ans;
int head,tail,que[maxN+];
int cnt,val[*maxN+],sum[*maxN+]; int main()
{
freopen("bzoj1149.in","r",stdin);
freopen("bzoj1149.out","w",stdout);
int i;
N=gint();
dep[]=;
re(i,,N)
{
a[i].fi=gint(),a[i].se=gint();
if(a[i].fi!=-)dep[a[i].fi]=dep[i]+;
if(a[i].se!=-)dep[a[i].se]=dep[i]+;
}
ans=;
re(i,,N)upmax(maxdep,dep[i]);
re(i,,N)if(a[i].fi==- || a[i].se==-)if(maxdep-dep[i]>){ans=-;break;}
if(ans==-){cout<<ans<<endl;return ;}
que[head=tail=]=;
re(i,,maxdep-)
{
int temp=tail;
while(head<=temp)
{
int u=que[head++];
que[++tail]=a[u].fi;
que[++tail]=a[u].se;
}
}
re(i,head,tail)
{
int u=que[i];
val[++cnt]=(a[u].fi==-)?:;
val[++cnt]=(a[u].se==-)?:;
}
re(i,,N)sum[i]=sum[i-]+val[i];
int l=,r=cnt;
while(l<r)
{
int mid=(l+r)/;
int lf,rf;
if(sum[mid]-sum[l-]==mid-l+) lf=; else if(sum[mid]-sum[l-]==) lf=; else lf=;
if(sum[r]-sum[mid]==r-mid) rf=; else if(sum[r]-sum[mid]==) rf=; else rf=;
if(lf== && rf==) {ans=-;break;}
if(lf== && rf==) break;
if(lf== && rf==) {ans++;break;}
if(lf== && rf==) break;
if(lf== && rf==) break;
if(lf== && rf==) {ans++;l=mid+;continue;}
if(lf== && rf==) {l=mid+;continue;}
if(lf== && rf==) {r=mid;continue;}
if(lf== && rf==) {ans++;r=mid;continue;}
}
cout<<ans<<endl;
return ;
}
05-04 12:06