几个做题的小技巧:
- 通过挖掘题目的特殊性质,找到分析问题的切入点
- 更换统计答案的方式
- 特殊性质优化
- 模型等效替换
深度优先搜索 (depth first search,dfs)
适用问题:能把待求解的问题分成不太多的步骤,每个步骤又只有不太多的选择。
dfs 模板:
void dfs(int dep,...){//正在完成问题的第dep步
如果已经完成最后一步,则返回;
完成第dep步;
dfs(dep+1,...);
} 它的本质上是一种走不通就掉头的思想。有些问题在往下一步搜索时,每一步都出现很多分支,为了求得问题的解,我们必须对每一个分支都要试探,看看是否符合题目要求,若发现某一步试探不合要求,则停止从该分支往下的试探,立即返回到上一步去试探其它分支,直到找到问题的解。如果回溯到问题的初始状态之后还要返回,则表示该问题无解。
-
剪枝
- 可行性剪枝
在搜索的过程中,及时对当前状态进行检查,如果发现分支已经无法到达递归边界,就执行回溯。这就好比我们在路上走时,远远看到前方是一个死胡同,就应该立即折返绕路,而不是走到路的尽头再返回。- 上下界剪枝
在最优化问题的搜索过程中,如果当前花费的代价已经超过当前搜到的最优解,那么无论采取多么优秀的策略到达递归边界,都不可能更新答案。此时可以停止对当前分支的搜索,执行回溯,本质上就是考虑极端情况。
例题:P1219 (USACO1.5) 八皇后 Checker Challenge
AC code
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 35;
int n,ans,a[MAXN];
bool vis[3][MAXN] = {0};
void print(){
for(int i = 1;i <= n;++i){
printf("%d ",a[i]);
}
cout << endl;
}
void search(int i){
if(i == n + 1){
ans++;
if(ans <= 3)
print();
return ;
}
for(int j = 1;j <= n;++j)
if(!vis[0][j] && !vis[1][i + j] && !vis[2][i - j + n - 1]){
a[i] = j;
vis[0][j] = vis[1][i + j] = vis[2][i - j + n - 1] = 1;
search(i + 1);
vis[0][j] = vis[1][i + j] = vis[2][i - j + n - 1] = 0;
}
}
int main(){
cin >> n;
search(1);
printf("%d\n",ans);
return 0;
}-
回溯
每次递归进入深一层,进行标记;从深层返回后,清除标记。这个方法就叫做回溯。
-
洪水填充 (floodfiil)
例题 P1451 求细胞数量
AC Code
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 105;
int m,n;
char field[MAXN][MAXN];
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
int colorCount;
void floodfill(int x,int y){
field[x][y] = 0;
for(int k = 0;k < 4; ++k){
int xx = x + dx[k];
int yy = y + dy[k];
if(xx > 0 && xx <= m && yy > 0 && yy <=n){
if(field[xx][yy]>='1' && field[xx][yy] <='9')
floodfill(xx,yy);
}
}
}
int main(){
cin>>m>>n;
for(int i = 1;i <= m;++i){
for(int j = 1;j <= n; ++j){
cin>>field[i][j];
}
}
for(int i=1;i<=m;++i){
for(int j=1;j<=n;++j){
if(field[i][j]>='1'&&field[i][j]<='9'){
colorCount++;
floodfill(i,j);
}
}
}
cout<<colorCount<<endl;
return 0;
}广度优先搜索算法 (breadth first search,bfs)
特点:先尝试在本层枚举,如果本层没有答案,则去下一层枚举下一层的所有可能性。
要了解广度优先搜索算法,首先要了解队列。
队列:
- 顺序队列
顺序队列的基本操作:
(1) 初始化:head = tail = 0,这时候队列中没有元素,为空。
(2)x 元素入队:q[tail++]=x;
(3) 队首元素赋值给 a 并出队:
a=q[head++];
(4) 队列为空的条件:
head==tail
(5) 队列中元素个数:
tail-head
PS:也可以使用 STL 中的 queue 来实现哦!- 循环队列
具体循环队列的基本操作如下:
“队列初始化”与“判断队列是否为空”与顺序队列是一样的;
进队 (插入元素 x):如果队列未满则执行q[tail]=x;tail=(tail + 1)% m; 出队:如果队列不为空,则返回队首元素 q[head],同时head=(head + 1)% m。
队列中元素个数:(tail-head+m)% m;- 单调队列
单调队列是一种特殊的队列,它能在队列两端进行删除操作,并始终维护队列保持一种单调性。
以单调递增队列为例,它要求队列中的元素始终保持单调递增,新元素入队时,先将队尾比新元素值更大的元素剔除出队列后,再将新元素入队。这保证了队列中所有元素单调递增。
例如:队列中元素 ,则 入队时,先将 和 剔除出队,再将 入队,队列中的元素为: 。
顺序队列模板题:B3616 【模板】队列
AC Code(STL)
#include<bits/stdc++.h>
using namespace std;
queue<int>q;
int n,x,num;
int main(){
cin>>n;
while(n--){
cin>>num;
if(num==1){
cin>>x;
q.push(x);
}else if(num==2){
if(q.empty())puts("ERR_CANNOT_POP");
else q.pop();
}else if(num==3){
if(q.empty())puts("ERR_CANNOT_QUERY");
else cout<<q.front()<<endl;
}else cout<<q.size()<<endl;
}
return 0;
}单调队列模板题:P1886【模板】单调队列 / 滑动窗口
AC Code
#include<bits/stdc++.h>
using namespace std;
int n,k;
int nums[20000005];
int q[20000005],head,tail;
int q1[20000005],head1,tail1;
vector<int>v1,v2;
int main(){
cin >> n >> k;
for(int i = 0;i < n;++i)cin >> nums[i];
for(int i = 0;i < n;++i){
while(tail - head != 0 && nums[q[tail - 1]] <= nums[i])tail--;
while(tail1 - head1 != 0 && nums[q1[tail1 - 1]] >= nums[i])tail1--;
q[tail++] = i;
q1[tail1++] = i;
while(q[head] <= i - k)head++;
while(q1[head1] <= i - k)head1++;
if(i >= k - 1){
v1.push_back(nums[q[head]]);
v2.push_back(nums[q1[head1]]);
} }
for(int i = 0;i < v2.size();++i)cout << v2[i] << ' ';
cout << endl;
for(int i = 0;i < v1.size();++i)cout << v1[i] << ' ';
return 0;
}- 单调队列的性质:
对单调递增队列而言:
元素 k 入队时,其在单调队列中左边的元素即为元素 k 入队前的所有元素中,从右往左第一个比 k 小的元素。
元素 k 出队时,将其“挤”出单调队列的元素,即为在 k 之后入队的所有元素中,第一个小等于 k 的元素。
bfs 模板:
void bfs()
{
初始结点入队
记录状态
while(队列非空)
{
取出队首元素u
遍历所有相邻且还未访问过的元素v
{
将v点加入队列
记录状态
如果v点为目标结点,返回相关信息。结束。
}
u点出队
}
}
例题:P1443 马的遍历
AC Code
#include<bits/stdc++.h>
using namespace std;
int n,m,x,y;
int board[405][405];
int dx[] = {-2,-2,-1,-1,1,1,2,2};
int dy[] = {-1,1,-2,2,-2,2,-1,1};
void bfs(int startX,int startY){
memset(board,-1,sizeof(board));
queue<int>q;
q.push(startX);
q.push(startY);
board[startX][startY] = 0;
while(!q.empty()){
int x = q.front();
q.pop();
int y = q.front();
q.pop();
for(int i = 0; i < 8;++i){
int xx = x + dx[i];
int yy = y + dy[i];
if(xx > 0 && xx <= n && yy > 0 && yy <= m && board[xx][yy] == -1){
board[xx][yy] = board[x][y] + 1;
q.push(xx);
q.push(yy);
}
}
}
}
int main(){
scanf("%d%d%d%d",&n,&m,&x,&y);
bfs(x,y);
for(int i = 1;i <= n;++i){
for(int j = 1;j <= m;++j){
printf("%-5d",board[i][j]);
}
printf("\n");
}
return 0;
}下面再看一个例子:P1141 01 迷宫
AC Code
#include<bits/stdc++.h>
using namespace std;
int maze[1005][1005];
int color[1005][1005];
int n,m;
int nextColor;
int colorCount[1000005];
const int dx[4] = {0,1,0,-1};
const int dy[4] = {1,0,-1,0};
int bfs(int x,int y){
if(color[x][y] != -1){
return colorCount[color[x][y]];
}
int count = 1;
queue<int>q;
color[x][y] = nextColor;
q.push(x);
q.push(y);
while(!q.empty()){
x = q.front();
q.pop();
y = q.front();
q.pop();
for(int i = 0; i < 4;++i){
int nx = x + dx[i];
int ny = y + dy[i];
if(!(nx > 0 && nx <= n && ny > 0 && ny <= n))continue;
if(color[nx][ny] == -1 && maze[nx][ny] != maze[x][y]){
color[nx][ny] = nextColor;
count++;
q.push(nx);
q.push(ny);
}
}
}
colorCount[nextColor] = count;
nextColor++;
return count;
}
int main(){
cin >> n >> m;
for(int i = 1;i <= n;++i){
for(int j = 1; j <= n;++j){
char c;
cin >> c;
maze[i][j] = c - '0';
}
}
memset(color,-1,sizeof(color));
nextColor = 0;
for(int i = 0;i < m;++i){
int x,y;
cin >> x >> y;
cout << bfs(x,y) << endl;
}
return 0;
}接下来是一个复杂一点的问题 P1379 八数码难题
AC Code
#include<bits/stdc++.h>
using namespace std;
struct Step{
int num;
string status;
int x,y;
};
int dx[] = {-1,1,0,0};
int dy[] = {0,0,-1,1};
int main(){
string start;
string end = "123804765";
cin >> start;
queue<Step> q;
for(int i = 0;i <= 8;++i){
if(start[i] == '0'){
int x = i / 3;
int y = i % 3;
q.push({0,start,x,y});
}
}
set<string>s;
s.insert(start);
while(!q.empty()){
Step p = q.front();
q.pop();
if(p.status == end){
cout << p.num << endl;
return 0;
}
string t = p.status;
int x = p.x;
int y = p.y;
int pos = x * 3 + y;
for(int k = 0;k < 4;++k){
int xx = x + dx[k];
int yy = y + dy[k];
if(xx >= 0 && xx <= 2 && yy >= 0 && yy <= 2){
int nextpos = xx * 3 + yy;
swap(t[pos],t[nextpos]);
if(s.count(t) == 0){
q.push({p.num + 1,t,xx,yy});
s.insert(t);
}
swap(t[pos],t[nextpos]);
}
}
}
return 0;
}前缀和 & 差分
-
前缀和
用于求区间和。
for(int i=1;i<=n;i++) pre[i]=pre[i-1]+a[i];
前缀和模板题B3612 【深进1.例1】求区间和
AC Code
#include<bits/stdc++.h>
using namespace std;
int n,a[100005],m,l,r,pre[100005];
int main(){
cin >> n;
for(int i = 1;i <= n;++i)cin >> a[i];
for(int i = 1;i <= n;++i)pre[i] = pre[i - 1] + a[i];
cin >> m;
while(m--){
cin >> l >> r;
cout << pre[r] - pre[l - 1] << endl;
}
return 0;
}-
差分
for(int i = 1;i <= n;++i)d[i] = a[i] - a[i - 1];可快速修改一个区间里的数,使这个区间里的数字同时增加 。
差分模板题:P2367 语文成绩
AC Code
#include<bits/stdc++.h>
using namespace std;
int n,p,nums[5000005],x,y,z,ans = 0x7fffffff;
int d[5000005];
int main(){
cin >> n >> p;
for(int i = 1;i <= n;++i){
cin >> nums[i];
d[i] = nums[i] - nums[i - 1];
}
while(p--){
cin >> x >> y >> z;
d[x] += z;
d[y + 1] -= z;
}
for(int i = 1;i <= n;++i)nums[i] = nums[i - 1] + d[i];
for(int i = 1;i <= n;++i)if(nums[i] < ans)ans = nums[i];
cout << ans << endl;
return 0;
}栈 & 链表
-
栈
栈是限定仅在标为进行插入或删除操作的线性表。 栈的模板题。B3614 【模板】栈
AC Code
#include<bits/stdc++.h>
using namespace std;
stack<unsigned long long>s;
string s1;
unsigned long long t,n,ans;
int main(){
cin>>t;
while(t--){
cin>>n;
while(n--){
cin>>s1;
if(s1=="push"){
cin>>ans;
s.push(ans);
}else if(s1=="pop"){
if(s.empty())cout<<"Empty"<<endl;
else s.pop();
}else if(s1=="query"){
if(s.empty())cout<<"Anguei!"<<endl;
else cout<<s.top()<<endl;
}else cout<<s.size()<<endl;
}while(!s.empty())s.pop();
}
return 0;
}经典问题:括号匹配。
B2165 括号匹配
AC Code
#include<bits/stdc++.h>
using namespace std;
stack<char>stk;
string s;
int n;
char ch[128];
bool check(string s){
while(!stk.empty())stk.pop();
for(char c:s){
if(ch[c]==0){//是左半
stk.push(c);
}else if(!stk.empty() && stk.top() == ch[c]){//匹配上了
stk.pop();
}else {//没匹配上
return false;
}
}
return stk.empty();
}
int main(){
cin>>n;
ch[')']='(';
ch[']']='[';
ch['}']='{';
while(n--){
cin>>s;
puts(check(s)?"YES":"NO");
}
return 0;
}-
链表
- 查询序列中第 i 个元素:时间复杂度
int GetPos(int pos)//求链表第pos个元素的存储位置
{
int hd=Head;
for(int j=1;j<pos;j++)hd=nxt[hd];
return hd;
}- 在第 i 个元素前加入新的元素 v:时间复杂度 (查找到第 i 个元素需要 )
void InsertValue(int pos,int val)//在第pos个元素前插入新元素val
{
int p=GetPos(pos-1);
Value[++n]=val;
nxt[n]=nxt[p];
nxt[p]=n;
}- 删除序列中的第 i 个元素:时间复杂度 (查找到第 i 个元素需要 )
void DeleteValue(int pos)//删除第pos个元素
{
int p=GetPos(pos-1);
nxt[p]=nxt[nxt[p]];
}当然也可以使用数组模拟。
PS:也可以使用 STL 中的 list 哦!