CSU1581: Clock Pictures(KMP)

Description

CSU1581: Clock Pictures(KMP)_第1张图片

Input

CSU1581: Clock Pictures(KMP)_第2张图片

Output

CSU1581: Clock Pictures(KMP)_第3张图片

Sample Input

6
1 2 3 4 5 6
7 6 5 4 3 1

Sample Output

impossible

HINT

Source

NCPC 2014



题意:给出时针的角度,看两个时钟是否匹配

思路:对于连续数字的匹配问题,明显KMP搞起,next数组的运用


#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
#define ls 2*i
#define rs 2*i+1
#define up(i,x,y) for(i=x;i<=y;i++)
#define down(i,x,y) for(i=x;i>=y;i--)
#define mem(a,x) memset(a,x,sizeof(a))
#define w(a) while(a)
#define LL long long
const double pi = acos(-1.0);
#define Len 200005
#define mod 360000
const int INF = 0x3f3f3f3f;
#define exp 1e-6
 
int n,a[Len],b[Len],s[Len*2],next1[Len];
 
void get_next()
{
    next1[0] = 0;
    int i;
    up(i,2,n-1)
    {
        int t = i-1;
        t = next1[t];
        w(t!=0 && a[t+1]!=a[i]) t = next1[t];
        t++;
        if(a[t]==a[i]) next1[i] = t;
        else next1[i] = 0;
    }
}
 
int main()
{
    int i,j,k;
    w(~scanf("%d",&n))
    {
        up(i,0,n-1)
        scanf("%d",&a[i]);
        up(i,0,n-1)
        scanf("%d",&b[i]);
        sort(a,a+n);
        sort(b,b+n);
        down(i,n-1,1)
        a[i]=(a[i]-a[i-1]+mod)%mod;
        up(i,0,n-1)
        s[i]=s[i+n]=b[i];
        down(i,2*n-1,1)
        s[i]=(s[i]-s[i-1]+mod)%mod;
        int flag = 0;
        int pos = 1;
        get_next();
 
        up(i,1,2*n-1)
        {
            if(s[i]!=a[pos])
            {
                int tem = next1[pos-1];
                w(tem && s[i]!=a[tem+1])
                tem = next1[tem];
                tem++;
                if(a[tem]==s[i]) pos = tem+1;
                else pos = 1;
            }
            else pos++;
            if(pos == n)
            {
                flag = 1;
                break;
            }
        }
        printf("%s\n",flag?"possible":"impossible");
    }
 
    return 0;
}


你可能感兴趣的:(KMP,CSU)