跳到正文

算法·理论

模板

Love_Me_约 3 分钟
原文

这是 2026年11月16日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年11月16日
收录
2026年11月16日
更新
2026年11月23日
篇幅
约 3 分钟
获赞
1

版本

  1. v3当前
  2. v2
  3. v1

ST表

[https://www.luogu.com.cn/problem/P3865]

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define INF 0x3f3f3f3f3f3f3f3f
#define endl '\n'
const int N=1e5+10;
int n,m,a[N],st[N][20];
int quary(int l,int r){
	int len=log2(r-l+1);
	int a=st[l][len];
	int b=st[r-(1<<len)+1][len];
	return max(a,b);
}
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		st[i][0]=a[i];
	}
	for(int i=1;(1<<i)<=n;i++){
		for(int j=1;j+(1<<i)-1<=n;j++){
			int len=(1<<(i-1));
			st[j][i]=max(st[j][i-1],st[j+len][i-1]);
		}
	}
	while(m--){
		int a,b;
		cin>>a>>b;
		cout<<quary(a,b)<<endl;
	}
	return 0;
}

SPFA

C++
[https://www.luogu.com.cn/problem/P3385]


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define INF 0x3f3f3f3f3f3f3f3f
int T,n,m,q,dis[2005],cnt[2005]; 
bool st[2005];
struct node{
	int v,w;
};
vector<node>adj[2005];
bool spfa(int s){
	memset(cnt,0,sizeof cnt);
	queue<int>q;
	q.push(s);
	st[s]=1;
	dis[s]=0;
	while(!q.empty()){
		int h=q.front();
		q.pop();
		st[h]=0;
		if(cnt[h]>n) return 1; 
		for(node x:adj[h]){
			if(dis[x.v]>dis[h]+x.w){ 
				dis[x.v]=dis[h]+x.w; 
				cnt[x.v]=cnt[h]+1; 
		        if(!st[x.v]){
		            st[x.v]=1;
					q.push(x.v); 
				}
			}
		}
		
	}
	return 0; 
}
signed main(){
	cin >> T;
	while(T--){
		memset(adj,0,sizeof adj);
		memset(st,0,sizeof st);
		memset(dis,INF,sizeof dis);
		cin >> n >> m;
		while(m--){ 
			int u,v,w;
			cin>>u>>v>>w;
			if(w>=0){
				adj[u].push_back({v,w});
				adj[v].push_back({u,w});
			}	
			else adj[u].push_back({v,w});
		}
		int num=spfa(1);
		if(num==1) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	}
	return 0;
}