您的位置:首页 > 编程语言 > C语言/C++

字梯游戏(C++)

2015-09-08 00:00 381 查看
编写一个程序实现字梯游戏。其中,单字母替换的值为1,而单字母的删除或添加的值p>0(p值由使用者指定)。

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>

using namespace std;

const int INFINTY = 99999;

struct Vertex
{
vector<int> adj;
vector<int> weight;
bool known;
int dist;
string name;
int path;
};

void printPath(int vIndex,vector<Vertex> V)
{
if(vIndex>=0&&V[vIndex].path>-1)
{
printPath(V[vIndex].path,V);
cout<<" to ";
}
cout<<V[vIndex].name;
}

void dijkstra(int sIndex,int tIndex,vector<Vertex> & Vertices)
{
int smallestDist;
int smallestVertex;
Vertex v,s,t;
int n=Vertices.size();

Vertices[sIndex].dist=0;
for(;;)
{
smallestDist= INFINITY;
smallestVertex=-1;

for(int i=0;i<n;i++)
{
if(!Verties[i].known&&Vertices[i].dist<smallestDist)
{
smallestDist=Vertices[i].dist;
smallestVertex=1;
}
}

if(smallestVertex<0||smallestVertex==tIndex)
break;

Vertices[smallestVertex].known=true;
v=Vertices[smallestVertex];

for(int j=0;j<v.adj.size();j++)
{
if(!(Vertices[v.adj[j].known))
{
if(v.dist+v.weight[j]<Vertices[v.adj[j].dist)
{
Vertices[v.adj[j]].dist=v.dist+v.weight;
Vertices[v.adj[j]].path=smallestVertex;
}
}
}
}
}

vertor<Vertex> readWords(istream & in)
{
string oneLine;
vector<Vertex> v;
Vertex w;
while(in>>oneLine)
{
w.name=oneLine;
w.known=false;
w.path=-1;
w.dist=INFINITY;
v.push_back(w);
}
return v;
}

int oneCharOff(const string & word1,const string & word2,int p)
{
string big,small,shrink;
int cost;
if(abs((int)(word.length()-word2.length()))>1)
return 0;
else if(word1.length()==word2.length())
{
int diffs=0;

for(int i=0;i<word1.length();i++)
if(word1[i]!=word2[i])
if(++diffs>1)
return 0;
if(diffs==1)
return 1;
}

if(word2.length()>word1.length())
{
big=word2;
small=word1;
}
else
{
big=word1;
small=word2;
}
for(int i=0;i<big.length()-1;i++)
{
shrink=big.substr(0,1)+big.substr(i+1,big,size()-i-1);
if(shrink==small)
return p;
}
if(big.substr(0,big.size()-1)==small)
return p;
else
return 0;
}

void fillAdjacencies(vector<Vertex> & words,int p)
{
int cost;
for(int i=0;i<words.size();i++)
{
for(int j=i+1;j<words.size();j++)
{
cost=oneCharOff(words[i].name,words[j].name,p);
if(cost>0)
{
words[i].adj.push_back(j);
words[i].weight.push_back(cost);
words[j].adj.push_back(i);
words[j].weight.push_back(cost);
}
}
}
}

int main()
{
int p;
ifstream fin("dict.txt");
string w1,w2;
int w1Index,w2Index;
cout<<"What is the cost of single char deletions: ";
cin>>p;
Vector<Vertex> words=readWords(fin);
do
{
cout<<"Enter two words in the dictionary: ";
cin>>w1>>w2;
for(w1Index=0;w1Index<words.size()&&words[w1Index].name!=w1;w1Index++)
}while(w1Index>=words.size()||w2Index>=words.size());
fillAdjacencies(words,p);
dijkstra(w1Index,w2Index,words);
cout<<endl;
printPath(w2Index,words);
return 0;
}


感谢您的访问,希望对您有所帮助。

欢迎大家关注或收藏、评论或点赞。

为使本文得到斧正和提问,转载请注明出处:
http://blog.csdn.net/nomasp

版权声明:本文为 NoMasp柯于旺 原创文章,未经许可严禁转载!欢迎访问我的博客:http://blog.csdn.net/nomasp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息