第一题
输入N个字符,求他们有多少种排列
abc 6种:abc acb......
aab 3种
N<=8
数列范围较小,所以直接全排列,暴力判重,就是不知道为啥一个点一直没过。。。
判断读入为空的原因??
#include<iostream>
#include<cstring>
using namespace std;
int g[100000][10];
int a[10];
int c[10];
bool b[10];
int n,gi=0,ans=0;
string s;
bool check(int x){ //T 不相等
for (int i=1; i<=n; i++)
if (g[x][i]!=c[i]) return true;
return false;
}
void dfs(int x){
if (x>n){
bool flag=true;
for (int i=1; i<=gi; i++)
if (check(i)==false) flag=false;
gi++;
if (flag==true){
for (int i=1; i<=n; i++)
g[gi][i]=c[i];
ans++;
}
return;
}
for (int i=1; i<=n; i++)
if (b[i]==0){
c[x]=a[i];
b[i]=1;
dfs(x+1);
b[i]=0;
}
}
int main(){
cin>>s;
if (s.empty()){
cout<<0<<endl;
return 0;
}
n=s.length();
for (int i=0; i<n; i++)
a[i+1]=s[i]-96;
/*for (int i=1; i<=n; i++)
cout<<a[i]<<endl;*/
dfs(1);
cout<<ans<<endl;
return 0;
}
第二题
长度为N的字符串,删除K个后使其字典序最小。
N<=10^5
分析:
1.一直升序的序列,没必要删除,因为你删除了它只会让答案更差
例如 abcde 就目前来看,删除b或者c等是没有意义的
2.降序的地方删除可以让答案更优
例如abca 很明显 c a处降序了,这个降序字符可以优化答案,
如果只能删除一个字符,那么c删除了对答案是有贡献的,如果可以删除两个,bc都需要删除
删除到不再降序的时候,这个降序的字符就不能再对前面进行优化了。
贪心算法:
当出现一个降序字符时,将他之前的比他大的字符全部删除(满足k的情况下)
当没有降序字符时,从末尾挨个删除。
#include<iostream>
#include<cstring>
using namespace std;
string s;
bool b[100005];
int n,k;
int main(){
cin>>s;
cin>>k;
while (k>0){
int i=0;
while (s[i]<=s[i+1]) i++;
//cout<<i<<endl;
while ((k>0)&&(s[i]>s[i+1])) {
s.erase(i,1); i--;
k--;
//cout<<s[i]<<" x "<<s[i+1]<<endl;
}
}
cout<<s<<endl;
return 0;
}
第三题
求一个图的最短路,并且这个最短路满足一个属性。
每条路有长度和花费金币两个参数,要求一路上花费的金币数量不能超过限定值。
100个点 10000条边
暴力搜索加剪枝
#include<iostream>
using namespace std;
struct orz{
int u,v,w,f;
int next;
};
orz e[10005];
int last[105];
bool b[105];
int k,n,m,ans=1000000;
int u,v,w,f;
int tot=0;
void dfs(int now,int zf,int zl){
if (zf>k) return ;
if (zl>ans) return ;
if (now==n) {
//cout<<12345<<endl;
ans=min(ans,zl);
return ;
}
int j=last[now];
while (j!=0){
int x=e[j].v;
if (b[x]==0){
b[x]=1;
dfs(x,zf+e[j].f,zl+e[j].w);
b[x]=0;
}
j=e[j].next;
}
}
int main(){
cin>>k>>n>>m;
for (int i=1; i<=m; i++){
cin>>u>>v>>w>>f;
tot++;
e[tot].u=u;
e[tot].v=v;
e[tot].w=w;
e[tot].f=f;
e[tot].next=last[u];
last[u]=tot;
}
//cout<<123<<endl;
b[1]=1;
dfs(1,0,0);
cout<<ans<<endl;
return 0;
}