http://acm.timus.ru/problem.aspx?space=1&num=1682
记录取模的余数,并查集。
View Code
const int MM = 511111; #define debug puts("wrong") typedef __int64 int64; int64 N; bool vis[MM]; vector<int64>g[MM]; vector<int64>gg[MM]; //^2 int64 fa[MM], ran[MM]; int64 getfa(int64 x) {return x==fa[x]?x:fa[x]=getfa(fa[x]);} void get_init() { for(int64 i=0;i<MM;i++) fa[i]=i, ran[i]=0; } void join(int64 x,int64 y) { if(ran[x]>ran[y]) fa[y]=x; else { fa[x]=y; if(ran[y]==ran[x]) ran[y]++; } } void solve() { int64 i,j,k,tmp,tt,xx,yy,v; bool ff; for(i=0;i<MM;i++) g[i].clear(),gg[i].clear(); get_init(); if(N==1) {printf("3\n");return;} for(i=1;i<MM;i++) { tmp=(i*i)%N, tt=i%N; for(j=0;j<g[N-tmp].size();j++) { v=g[N-tmp][j]; xx=getfa(i), yy=getfa(v); if(xx==yy) {printf("%I64d\n",i);return;} else join(xx,yy); } for(j=0;j<gg[N-tt].size();j++) { v=gg[N-tt][j]; if((i*i+v)%N==0) continue; xx=getfa(i), yy=getfa(v); if(xx==yy) {printf("%I64d\n",i);return;} else join(xx,yy); } gg[tmp].push_back(i); g[tt].push_back(i); } printf("-1\n"); } int main() { // freopen("out.txt","w",stdout); while(scanf("%I64d",&N)!=EOF) solve(); return 0; }