您的位置:首页 > 其它

传纸条(一)

2016-05-02 13:33 288 查看





这一道题和郑州轻工业的那次校赛的捡金子的题是一样的 , 当时上就就用了搜索 , 这一道题又试了试思路是 先从右下角到左上角赖以搜索 , 找到好心度最高的那一条路然后将该路线归零 , 然后再来搜索一次 , 将来两次的好心度相加 就是最终的结果 , 然后发现这不是最优解 , 这种两次的搜索是一种贪心的思想贪心只是一种概率上的最优解 , 下面附上 , 上述思想的代码 , 和能看出来非最优解的 数据

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<set>
#include<stack>
#include<string>
#include<sstream>
#include<map>
#include<cctype>
#include<limits.h>
using namespace std;
int n,m,a[55][55],visited[55][55],b[2][2]={-1,0,0,-1},result,flag,mark;
struct node
{
int x,y,step;
friend bool operator<(node s1,node s2)
{
return s1.step<s2.step;
}
};
priority_queue<node>Q;
void BFS(int y,int x)
{
node q={x,y,a[y][x]};
visited[y][x]=1;
Q.push(q);
while(!Q.empty())
{
node e=Q.top();
Q.pop();
for(int i=0;i<2;i++)
{
q.x=e.x+b[i][0],q.y=e.y+b[i][1];
if(q.x>=0&&q.x<m&&q.y>=0&&q.y<n&&!visited[q.y][q.x])
{
visited[q.y][q.x]=1;
q.step=e.step+a[q.y][q.x];
Q.push(q);
if(q.x==0&&q.y==0)
{
result+=q.step;
flag=1;
break;
}
}
}
if(flag)
{
while(!Q.empty())
Q.pop();
}
}
}
void DFS(int y,int x,int step)
{
if(step==result||mark)
{
a[y][x]=1;
return;
mark=1;
}
DFS(y-1,x,step+a[y-1][x]);
if(step==result||mark)
{
a[y][x]=1;
return;
mark=1;
}
DFS(y,x-1,step+a[y][x-1]);
if(step==result||mark)
{
a[y][x]=1;
return;
mark=1;
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
scanf("%d",&a[i][j]);
memset(visited,0,sizeof(visited));
mark=result=flag=0;
BFS(n-1,m-1);
DFS(n-1,m-1,0);
printf("%d\n",result);
}
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: