0%

2018去哪网春招笔试

2018去哪网春招笔试

原型题目:http://oj.leetcode.com/problems/word-ladder/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>

using namespace std;

int main()
{
freopen("in","r",stdin);

string st,en,str;
vector<string> arr;
pair<string, int> now;
queue<pair<string, int> > que;
bool ans = false;
cin>>st;

en=st;
reverse(en.begin(), en.end());//创建终点
while(cin>>str)
arr.push_back(str);
arr.push_back(en);
//for(auto it=arr.begin(); it!=arr.end(); it++)
// cout<<*it<<endl;
que.emplace(st, 1);//将起点加入点集
while(!que.empty())
{
//取出队列首部
now = que.front();
//cout<<now.first<<" "<<now.second<<endl;
que.pop();
if(now.first==en)
{
//找到终点,输出当前路径数
cout << now.second << endl;
return 0;
}
//超过最大转换次数继续寻找
if(now.second>99)
continue;
//遍历arr查找
for(auto it=arr.begin(); it!=arr.end(); it++)
{
//比较当前路径与下一路径的字符是否只差1,差1加入队列
string tmp=now.first,tmp2=*it;
int sum=0,len=tmp.length();
for(int i=0;i<len;i++)
if(tmp[i]!=tmp2[i])
sum++;
if (sum == 1)
que.emplace(*it, now.second + 1);
}
}
cout<<"0"<<endl;
return 0;
}

DFS+剪枝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cstring>
#define maxn 100000
int a[maxn],b[1010],n,m,ans,siz;
using namespace std;

void dfs(int j,int siz)
{
if(siz>ans)
ans=siz;
if(j==-1)
return ;
for(int i=j;i>=0;i--){
if(siz+a[i]<=m&&siz+b[i]>ans){
dfs(i-1,siz+a[i]);
}
}
}

int main()
{
cin>>n>>m;
cin>>a[0];
b[0]=a[0];
for(int i=1;i<n;++i){
cin>>a[i];
b[i]=b[i-1]+a[i];
}
ans=0;
dfs(n-1,0);
if(ans==m)
cout<<"perfect"<<endl;
else
cout<<"good"<<endl;
return 0;
}

01背包只过80%

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cstring>
#define maxn 100000
int a[maxn],dp[maxn];;
using namespace std;
int main()
{
int n,m,ans=0;
cin>>n>>m;
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)
{
cin>>a[i];
ans+=a[i];
}

dp[0]=1;
for(int i=1;i<n;i++)
{
for(int j=m;j>=a[i];j--)
{
if(j>=a[i])
dp[j]+=dp[j-a[i]];
}
}

if(dp[m]>0''ans==m)
cout<<"perfect"<<endl;
else
cout<<"good"<<endl;

return 0;
}