洛谷OJ:P3846 [TJOI2007] 可爱的质数/【模板】BSGS(大步小步算法)

思路:BSGS模板题,并且该题由于b与p互质,因此我们可以直接使用朴素的BSGS算法求解,算法讲解链接:BSGS简易讲解

#include<set>
#include<map>
#include<queue>
#include<vector>
#include<string>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
#define maxn 100050
#define SQ 1005
#define ll long long
ll p,n,b;
ll q(ll x,ll y,ll m){
	ll res=1;
	x=x%m;
	while(y){
		if(y&1)
			res=res*x%m;
		x=x*x%m;
		y/=2;
	}
	return res;
}
ll BSGS(ll a,ll b,ll m){
	map<ll,ll> hs;
	ll cur=b*a%m,t=sqrt(m)+1;
	for(int B=1;B<=t;++B){
		hs[cur]=B;
		cur=cur*a%m;
	}
	ll at=q(a,t,m),now=at;
	for(int A=1;A<=t;A++){
		if(hs[now])
			return A*t-hs[now];
		now=now*at%m;
	}
	return -1;
}
int main(void){
	scanf("%lld%lld%lld",&p,&b,&n);
	ll ans=BSGS(b,n,p);
	if(ans==-1)
		printf("no solution\n");
	else
		printf("%lld\n",ans);
	return 0;
}

 

洛谷(Luogu)是一个非常受欢迎的在线算法题库网站,它包含了各种计算机科学题目,包括数据结构、算法等。P1862输油管道问题是关于动态规划的一种典型应用,通常涉及到计算最短路径或者最优解。 在这个特定的问题中,输油管道网络可能会包含节点(代表城市)和连接它们的管道,每个管道有容量和成本。目标可能是找到从起点到终点的成本最低的输油路线,使得总成本不超过给定的最大费用,并确保满足每条管道的最大通过量。 以下是解决这个问题的一个基本的C++代码框架,采用深度优先搜索(DFS)或广度优先搜索(BFS),结合贪心策略: ```cpp #include <vector> using namespace std; struct Edge { int to, cap, cost; }; class Solution { public: vector<pair<int, int>> dijkstra(vector<Edge>& edges, int s, int t) { // 初始化距离数组和前驱指针 vector<int> dist(n, INT_MAX); vector<int> prev(n, -1); dist[s] = 0; priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; pq.push({0, s}); while (!pq.empty()) { pair<int, int> cur = pq.top(); pq.pop(); int u = cur.second; if (dist[u] != cur.first) continue; // 已经是最小距离,跳过 for (auto& edge : edges[u]) { int v = edge.to; int new_cost = cur.first + edge.cost; if (edge.cap > 0 && new_cost < dist[v]) { dist[v] = new_cost; prev[v] = u; pq.push({new_cost, v}); } } } return prev; } private: int n; // 节点数 }; ``` 请注意,这只是一个简化的模板,实际代码需要处理细节如边界条件、数据有效性检查以及最终的输出部分。如果你想要完整的代码,可以在洛谷官网查看该题目的具体描述和样例输入输出,或者在网上找一些详细的教程和博客文章作为参考。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值