堆最佳化的 dijkstra
#include<bits/stdc++.h>
using namespace std;
#define N 100005
#define M N<<2
int head[N],Next[M],ver[M],edge[M];
int tot;
int dist[M];
bool vis[M];
priority_queue<pair<int,int>>Q;
void ADD(int x,int y,int z) {
ver[++tot] = y;
edge[tot] = z;
Next[tot] = head[x];
head[x] = tot;
}
void dijkstra(int s){
memset(dist,0x3f,sizeof(dist));
memset(vis,0,sizeof(vis));
dist[s] = 0;
Q.push(make_pair(0,s));
while(!Q.empty()){
int x = Q.top().second;
Q.pop();
if(vis[x]) continue;
vis[x] = 1;
for(int i = head[x];~i;i = Next[i]){
int y = ver[i];
if(dist[y]>dist[x]+edge[i]){
dist[y] = dist[x]+edge[i];
Q.push(make_pair(-dist[y],y));
}
}
}
}
int main() {
int n,m,s;
memset(head,-1,sizeof(head));
tot = -1;
cin>>n>>m>>s;
for(int i = 1;i<=m;i++){
int x,y,z;
cin>>x>>y>>z;
ADD(x,y,z);
}
dijkstra(s);
for(int i = 1;i<=n;i++){
cout<<dist[i]<<" ";
}
return 0;
}
求組合數
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define N 100005
#define p 998244353
int fac[N];
int KSM(int a,int b){
int res = 1;
a%=p;
for(;b;b>>=1,a = a*a%p)if(b&1) res = res*a%p;
return res;
}
int inv(int x){
return KSM(x,p-2);
}
int C(int n,int m){
return ((fac[n]*inv(fac[m]))%p*inv(fac[n-m]))%p;
}
signed main(){
fac[0] = 1;
for(int i = 1;i<=N-5;i++){
fac[i] = fac[i-1]*i;
}
while(1){
int n,m;
cin>>n>>m;
cout<<C(n,m)<<endl;
}
return 0;
}
最小生成樹
#include<bits/stdc++.h>
using namespace std;
#define N 100005
#define M N<<1
#define INF 0x3f3f3f3f
int F[N],n,m,sum,num;
struct E{
int x,y,z;
}edge[M];
void init(int n){
for(int i = 1;i<=n;i++){
F[i] = i;
}
}
bool cmp(E a, E b){
return a.z<b.z;
}
int Find(int x){
if(x == F[x]) return x;
return F[x] = Find(F[x]);
}
int kruskal(){
sort(edge+1,edge+m+1,cmp);
init(n);
for(int i = 1;i<=m;i++){
int x = Find(edge[i].x);
int y = Find(edge[i].y);
if(x == y) continue;
F[x] = y;
num++;
sum+=edge[i].z;
}
if(num == n-1) return sum;
else return INF;
}
int main(){
cin>>n>>m;
for(int i = 1;i<=m;i++){
cin>>edge[i].x>>edge[i].y>>edge[i].z;
}
int ans = kruskal();
if(ans == INF){
puts("orz");
}
else{
cout<<ans;
}
return 0;
}