A和B和C纯语法题
A、
#include <iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long LL;
int main()
{
string s;
cin>>s;
int l,r;
cin>>l>>r;
swap(s[l-1],s[r-1]);
cout<<s<<endl;
return 0;
}
B、
#include <iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<map>
using namespace std;
typedef long long LL;
int main()
{
map<int,int> mh;
int n;
scanf ("%d",&n);
for (int i=0;i<n*4-1;i++)
{
int x;
scanf ("%d",&x);
mh[x]++;
}
for (auto &[k,v]:mh)
{
if (v!=4)
{
cout<<k<<endl;
return 0;
}
}
return 0;
}
C、
#include <iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<set>
#include<vector>
using namespace std;
typedef long long LL;
int main()
{
cin.tie(0);
set<string> mh;
vector<string> ml;
int n,m;
scanf ("%d%d",&n,&m);
for (int i=0;i<n;i++)
{
string s;
cin>>s;
ml.push_back(s);
}
for (int i=0;i<m;i++)
{
string s;
cin>>s;
mh.insert(s);
}
for (string s:ml)
{
if (mh.count(s))
printf ("Yes\n");
else
printf ("No\n");
}
return 0;
}
D、
直接爆搜所有可能的情况。爆搜的时候时间复杂度是阶乘上升的,应选用好的爆搜写法,不然会TLE。
#include <iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<set>
#include<vector>
#define x first
#define y second
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
vector<PII> g;
int a[20][20];
int res = 0;
bool st[20];
int n;
void dfs(int u)
{
if (u==2*n)
{
int sum = 0;
for (int i=0;i<g.size();i++)
{
if (i==0)
sum = a[g[i].x][g[i].y-g[i].x-1];
else
sum=sum^(a[g[i].x][g[i].y-g[i].x-1]);
}
res = max(res,sum);
return;
}
if (st[u])
{
dfs(u+1);
}
else
{
for (int i=u+1;i<2*n;i++)
{
if (!st[i])
{
g.push_back({u,i});
st[i] = true;
st[u] = true;
dfs(u+1);
g.pop_back();
st[i] = false;
st[u] = false;
}
}
}
}
int main()
{
cin.tie(0);
memset(st,false,sizeof st);
scanf ("%d",&n);
for (int i=0;i<2*n-1;i++)
{
for (int j=0;j<2*n-i-1;j++)
{
scanf ("%d",&a[i][j]);
// cout<<a[i][j]<<' ';
}
// cout<<endl;
}
dfs(0);
printf ("%d\n",res);
return 0;
}
再把当时TLE的代码粘上,可以对比对比算算复杂度
#include <iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<set>
#include<vector>
#define x first
#define y second
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
vector<PII> g;
LL a[20][20];
LL res = 0;
bool st[20];
int n;
int cnt =0;
void dfs(int u)
{
if (u==n)
{
LL sum = 0;
for (int i=0;i<g.size();i++)
{
if (i==0)
sum = a[g[i].x][g[i].y-g[i].x-1];
else
sum=sum^(a[g[i].x][g[i].y-g[i].x-1]);
}
res = max(res,sum);
return;
}
for (int i=0;i<2*n;i++)
for (int j=i+1;j<2*n;j++)
{
if (!st[i]&&!st[j])
{
g.push_back({i,j});
st[i] = true;
st[j] = true;
dfs(u+1);
g.pop_back();
st[i] = false;
st[j] = false;
}
}
}
int main()
{
cin.tie(0);
memset(st,false,sizeof st);
scanf ("%d",&n);
for (int i=0;i<2*n-1;i++)
{
for (int j=0;j<2*n-i-1;j++)
{
scanf ("%lld",&a[i][j]);
}
}
dfs(0);
cout<<res<<endl;
return 0;
}