您的位置:首页 > 其它

uva 11916 Emoogle Grid (BSGS)

2013-08-03 10:27 459 查看
UVA 11916

  BSGS的一道简单题,不过中间卡了一下没有及时取模,其他这里的100000007是素数,所以不用加上拓展就能做了。

代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <map>

using namespace std;

template<class T> T gcd(T a, T b) { return b ? a : gcd(b, a % b);}
typedef long long LL;
void gcd(LL a, LL b, LL &d, LL &x, LL &y) {
if (b) { gcd(b, a % b, d, y, x); y -= a / b * x;}
else d = a, x = 1, y = 0;
}
const LL MOD = 100000007;
const int N = 555;

LL multi(LL a, LL p) {
LL ret = 1;
a %= MOD;
while (p > 0) {
if (p & 1) ret *= a, ret %= MOD;
a *= a, a %= MOD, p >>= 1;
}
return ret;
}
map<LL, int> id;
vector<LL> rec
;
LL mincol;

void bs(LL b, LL x, LL rt) {
id.clear();
for (int i = 0; i <= rt; i++) {
if (id.find(b) != id.end()) break;
id[b] = i;
b *= x, b %= MOD;
}
}

LL gs(LL b, LL x, LL r) {
LL cur = b;
//for (int i = 0; i < 50; i++) {
//if (cur == r) return mincol + i + 1;
//cur *= x, cur %= MOD;
//}
int rt = (int) ceil(sqrt((double) MOD)) + 1;
bs(b, x, rt);
LL st = multi(x, rt), p, q, d;
cur = 1;
for (int i = 0; i <= rt; i++) {
gcd(cur, MOD, d, p, q);
p %= MOD, p += MOD, p %= MOD, p *= r / d, p %= MOD;
if (id.find(p) != id.end()) return (LL) i * rt + id[p] + mincol + 1;
cur *= st, cur %= MOD;
}
return -1;
}

LL bf(LL b, LL x, LL r) {
LL cur = b;
for (int i = 0; i < MOD; i++) {
if (cur == r) return mincol + i + 1;
cur *= x, cur %= MOD;
}
return -1;
}
int main() {
//freopen("in", "r", stdin);
LL n, k, b, r, x, y, bres;
int T, cas = 1;
cin >> T;
while (T-- && cin >> n >> k >> b >> r) {
for (int i = 0; i < N; i++) rec[i].clear();
id.clear();
mincol = 1;
for (int i = 0; i < b; i++) {
cin >> x >> y;
if (id.find(y) == id.end()) id[y] = id.size() - 1;
rec[id[y]].push_back(x);
mincol = max(mincol, x);
}
bres = 1;
for (int i = 0, sz = id.size(); i < sz; i++) {
rec[i].push_back(0);
rec[i].push_back(mincol + 1);
sort(rec[i].begin(), rec[i].end());
for (int j = 1, szj = rec[i].size(); j < szj; j++) {
if (rec[i][j] - rec[i][j - 1] - 2 >= 0) bres *= k * multi(k - 1, (LL) rec[i][j] - rec[i][j - 1] - 2) % MOD, bres %= MOD;
}
}
LL tmp = k * multi(k - 1, mincol - 1);
bres *= multi(tmp, n - id.size());
bres %= MOD;
cout << "Case " << cas++ << ": ";
if (bres == r) { cout << mincol << endl; continue; }
int cnt = 0;
for (int i = 0, sz = id.size(); i < sz; i++) {
rec[i].pop_back();
if (rec[i][rec[i].size() - 1] == mincol) bres *= k, bres %= MOD, cnt++;
}
bres *= multi(k - 1, n - cnt);
bres %= MOD;
k = multi(k - 1, n);
cout << gs(bres, k, r) << endl;
//cout << bf(bres, k, r) << endl;
}
return 0;
}


View Code

——written by Lyon
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: