二分查找
#include<bits/stdc++.h>
using namespace std;
int n,i,x,a[100001];
int erfind(int s,int t,int x){
int mid,ans=-1;
while(s<t){
mid=(s+t)/2;
if(x==a[mid]){
ans=mid;
t=mid-1;
};
if(x<a[mid])t=mid-1;
if(x>a[mid])s=mid+1;
}
if(a[s]==x) ans=s;
return ans;
}
int main(){
cin>>n;
for(i=1;i<=n;i++)cin>>a[i];
cin>>x;
cout<<erfind(1,n,x)<<endl;
return 0;
}
BFS
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
int n;
bool visited[MAXN];
vector<int> graph[MAXN];
void BFS(int start) {
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int cur = q.front();
q.pop();
for (int i = 0; i < graph[cur].size(); i++) {
int neighbor = graph[cur][i];
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
visited[i] = false;
graph[i].clear();
}
int m;
cin >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
BFS(1);
return 0;
}
DFS
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
int n;
bool visited[MAXN];
vector<int> graph[MAXN];
void DFS(int cur) {
visited[cur] = true;
for (int i = 0; i < graph[cur].size(); i++) {
int neighbor = graph[cur][i];
if (!visited[neighbor]) {
DFS(neighbor);
}
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
visited[i] = false;
graph[i].clear();
}
int m;
cin >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
DFS(1);
return 0;
}
BFS(2)
#include <bits/stdc++.h>
using namespace std;
int main() {
const int MAXN = 1005;
int n;
bool visited[MAXN];
vector<int> graph[MAXN];
cin >> n;
for (int i = 1; i <= n; i++) {
visited[i] = false;
graph[i].clear();
}
int m;
cin >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
queue<int> q;
q.push(1);
visited[1] = true;
while (!q.empty()) {
int cur = q.front();
q.pop();
for (int i = 0; i < graph[cur].size(); i++) {
int neighbor = graph[cur][i];
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
return 0;
}
一维数组冒泡排序
#include<bits/stdc++.h>
using namespace std;
const int MAXN=11;
int main() {
int n;
int a[MAXN];
bool ok;
n=10;
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=n-1;i>=1;i--){
ok=true;
for(int j=0;j<i;j++){
if(a[j]<a[j+1]){
swap(a[j],a[j+1]);
ok=false;
}
}
if(ok==true) break;
}
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}