BZOJ 1407 Savage(拓展欧几里得)

这题的时间复杂度真玄学。。。 O(m*n^2)。1e8也能过啊。。。

首先题目保证m<=1e6. 这启发我们枚举或者二分答案?

但是答案不满足单调性,考虑从小到大枚举m。

对于每一个m,枚举两个野人在有生之年能否住在一起。可以推出一个同余方程,用扩欧可以求出最小整数解x,或者没有解。

如果x<=life[i]&&x<=life[j]那么当然不满足条件。

 

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi 3.1415926535
# define eps 1e-9
# define MOD 100000007
# define INF 1000000000
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<1,l,mid
# define rch p<<1|1,mid+1,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
    int res=0, flag=0;
    char ch;
    if((ch=getchar())=='-') flag=1;
    else if(ch>='0'&&ch<='9') res=ch-'0';
    while((ch=getchar())>='0'&&ch<='9')  res=res*10+(ch-'0');
    return flag?-res:res;
}
void Out(int a) {
    if(a<0) {putchar('-'); a=-a;}
    if(a>=10) Out(a/10);
    putchar(a%10+'0');
}
const int N=20;
//Code begin...

int C[N], P[N], L[N], n;

int extend_gcd(int a, int b, int &x, int &y){
    if (a==0&&b==0) return -1;
    if (b==0){x=1; y=0; return a;}
    int d=extend_gcd(b,a%b,y,x);
    y-=a/b*x;
    return d;
}
bool check(int ans){
    int d, x, y;
    FOR(i,1,n) FOR(j,i+1,n) {
        d=extend_gcd(P[i]-P[j],-ans,x,y);
        if ((C[j]-C[i])%d) continue;
        x*=((C[j]-C[i])/d);
        int k=abs(-ans/d);
        x=(x%k+k)%k;
        if (x<=L[i]&&x<=L[j]) return false;
    }
    return true;
}
int main ()
{
    int ans=0;
    scanf("%d",&n);
    FOR(i,1,n) scanf("%d%d%d",C+i,P+i,L+i), ans=max(ans,C[i]);
    for (;;++ans) if (check(ans)) break;
    printf("%d\n",ans);
    return 0;
}
View Code

 

posted @ 2017-03-17 20:27  free-loop  阅读(149)  评论(0编辑  收藏  举报