1282 时钟

1282 时钟
《1282 时钟》 题目来源:
Codility 基准时间限制:1 秒 空间限制:131072 KB 分值: 40
难度:4级算法题

《1282 时钟》 收藏

《1282 时钟》 关注 有N个时钟,每个时钟有M个指针,P个刻度。时钟是圆形的,P个刻度均分整个圆。每个时钟每个指针指向整数刻度,并且每个时钟自身指针指向的数字都不同。你可以任意旋转时钟的表盘,但是你不能转指针。问最后有多少对时钟可以变成相同的状态。

例如:N = 5,M = 2,P = 4,5个时钟的数据如下{1, 2} {2, 4} {4, 3} {2, 3} {1, 3}

《1282 时钟》

经过旋转后。 其中(1, 3), (1, 4), (2, 5) 和 (3, 4)是相同的。

《1282 时钟》

给出所有时钟的数据,求有多少对时钟是相同的。 Input

第1行:3个数N, M, P中间用空格分隔,其中N为时钟的数量,M为表针的数量,P为刻度的数量(1 <= M, N <= 500, 1 <= P <= 10^9, M <= P)。
第2 - N + 1行:每行M个数,对应一个时钟,M个指针的位置。

Output

输出有多少对时钟是相同的。

Input示例

5 2 4
1 2
2 4
4 3
2 3
1 3

Output示例

4
#include <iostream>
#include <string.h>
#include <map>
#include <set>
#include <vector>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int N = 1010;
const int seed = 71;
typedef unsigned long long ll;
ll base[N],h[N];
map<ll,int> mp;
int a[N];
void init()
{
    base[0] = 1;
    for(int i = 1; i < 1000; ++i)
    {
        base[i] = base[i - 1] * seed;
    }
}

void Hash(int n)
{
    for(int i = 0; i < n; ++i)
    {
        h[i] = 0;
        if(i) h[i] = h[i - 1] * seed;
        h[i] += a[i];
    }
}

ll get_interval(int l,int r)
{
    ll ans = h[r];
    if(l) ans -= h[l - 1] * base[r - l + 1];
    return ans;
}

void solve()
{
    init();
    int n,m,p,ans = 0;
    cin>>n>>m>>p;
    for(int i = 1; i <= n; ++i)
    {
        for(int j = 0; j < m; ++j)
        {
            scanf("%d",&a[j]);
        }
        sort(a,a + m);
        int temp = a[0];
        for(int j = 0; j < m - 1; ++j)
        {
            a[j] = a[j + 1] - a[j];
        }
        a[m - 1] = temp + p - a[m - 1];
        for(int j = 0; j < m; ++j) a[j + m] = a[j];
        Hash(m + m);
        bool ok = true;
        for(int j = 0; j < m; ++j)
        {
            ll tp = get_interval(j,j + m - 1);
            if(mp[tp])
            {
                ok = false;
                ans += mp[tp];
                mp[tp]++;
                break;
            }
        }
        if(ok)
        {
            mp[get_interval(0,m - 1)]++;
        }
    }
    cout << ans << endl;
}

int main() {
    solve();
    return 0;
}
点赞