首页 > 代码库 > Crazy Professor
Crazy Professor
Crazy Professor
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
Professor Nathan Mathan is crazy about mathematics. For an unknown reason, he started to write on the blackboard all positive integers starting from 1. After writing a new number a, Professor draws lines connecting it with all the numbers b that are already on the blackboard and satisfy at least one of the conditions:
- b + a · a ≡ 0 (mod k),
- a + b · b ≡ 0 (mod k),
Nobody can persuade him to stop this meaningless procedure. Professor says that he will stop as soon as there appears a cycle in the graph of the numbers on the blackboard. But only Professor knows when that will happen and whether it will happen at all. Help his colleagues determine after which number he will stop.
Input
You are given the integer k (1 ≤ k ≤ 100000).
Output
Output the number after which the first cycle will appear in the graph. If it never happens, output −1.
Sample
input | output |
---|---|
2 | 5 |
Notes
In example after Professor had written all integers from 1 to 4 the graph contained edges (1, 3) and (2, 4). After writing number 5, Professor connects it with numbers 1 and 3, so the cycle 1-5-3-1 appears in the graph.
分析:并查集+同余定理;
注意可能有两条重边,要排除;
代码:
#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>#include <algorithm>#include <climits>#include <cstring>#include <string>#include <set>#include <map>#include <queue>#include <stack>#include <vector>#include <list>#define rep(i,m,n) for(i=m;i<=n;i++)#define rsp(it,s) for(set<int>::iterator it=s.begin();it!=s.end();it++)#define mod 1000000007#define inf 0x3f3f3f3f#define vi vector<int>#define pb push_back#define mp make_pair#define fi first#define se second#define ll long long#define pi acos(-1.0)#define pii pair<int,int>#define Lson L, mid, rt<<1#define Rson mid+1, R, rt<<1|1const int maxn=2e5+10;using namespace std;ll gcd(ll p,ll q){return q==0?p:gcd(q,p%q);}ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p;p=p*p;q>>=1;}return f;}int n,m,k,t,p[maxn],now[maxn];vi mo[maxn];int find(int x){ return p[x]==x?x:p[x]=find(p[x]);}int main(){ int i,j; scanf("%d",&k); rep(i,1,maxn-10)p[i]=i; for(i=1;;i++) { ll q=((ll)i*i/k+1)*k; while((j=q-(ll)i*i)<i) { int x=find(j),y=find(i); if(x==y)return 0*printf("%d\n",i); else p[x]=y; now[j]=i; q+=k; } q=(ll)(i/k+1)*k; for(int x:mo[(q-i)%k]) { if(now[x]==i)continue; int y=find(x),r=find(i); if(y==r)return 0*printf("%d\n",i); else p[y]=r; } mo[(ll)i*i%k].pb(i); } //system("Pause"); return 0;}
Crazy Professor
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。