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); que.emplace(st, 1); while(!que.empty()) { now = que.front(); que.pop(); if(now.first==en) { cout << now.second << endl; return 0; } if(now.second>99) continue; for(auto it=arr.begin(); it!=arr.end(); it++) { 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; }
|