A - Rightmost 
input:abcdaxayz
output:7
题意为:求最后一个a出现的位置,没有的话就输出-1.
思路从后向前遍历一遍,如果遇到a就输出位置并结束,否者的话就输出-1.
#include <iostream>
using namespace std;
int main()
{
string str;
cin >> str;
int pos = -1;
for (int i = str.size() - 1; i >= 0; i--)
{
if (str[i] == 'a')
{
cout << i + 1 << endl;
return 0;
}
}
cout << pos << endl;
return 0;
}
B - Adjacency List
input:
6 6 3 6 1 3 5 6 2 5 1 2 1 6 output: 3 2 3 6 2 1 5 2 1 6 0 2 2 6 3 1 3 5
题意:有n个城市,每个城市会有m条路与之相连,每条路使得两个城市相互连接。输出从1-N的城市与其相连的个数,并输出其编号。
思路:我刚开始想到了邻接表的方式去做,可是奈何调不出来,最后被迫使用vector去做。既然每个城市会有若干个城市与他相联系,那么我们便可以使用vector去存储他们之间的关系,(一维代表城市,二维代表与他相关的城市)最后在对二维的城市进行一个排序,这样便可以实现其结果了。 (后来发现用set或者是map会更好写一点,毕竟自己就排序好了).
#include <iostream>
#include <vector>
#include <algorithm>
#define endl "\n"
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<vector<int>> res(n + 1);
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
res[a].push_back(b);
res[b].push_back(a);
}
for (int i = 1; i <= n; i++)
{
cout << res[i].size() << " ";
sort(res[i].begin(), res[i].end());
for (int x : res[i])
{
cout << x << " ";
}
cout << endl;
}
return 0;
}
C - Previous Permutation
input:
3
3 1 2output:
2 3 1
题意:求全排列中当前序列的的前一个(偷鸡了,直接使用STL中的prev_permutation函数直接秒了)不过我也补充了一下这个函数的实现方法。
代码如下:
#include <iostream>
#include <stdio.h>
#include <algorithm>
const int N = 1e5 + 10;
using namespace std;
int n, a[N];
void F()
{
int i, j, maxn;
for (i = n - 2; i >= 0; i--)
{
if (a[i] > a[i + 1])
{
maxn = n - 1;
for (j = n - 1; j > i; j--)
if (a[j] < a[i])
{
swap(a[i], a[j]);
break;
}
sort(a + i + 1, a + n, greater<int>());
break;
}
}
}
int main()
{
int m, i;
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
prev_permutation(a, a + n);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
D - Divide by 2 or 3
input:
3
1 4 3
output:3
题意:给我们一系列正整数,我们可以对这些数进行一些操作:对任意位置的数除以二,或者除以三。在进行一系列的重做后我们会得到一个新的数列,这个数列每个数都相等。
思路:开始开提前第一眼便看到了数据范围,就1000个数,我就准备写暴力算法了,然后看了一些题面,我发现了两个需要我们去解决的问题,其一便是我们该如何去找那个基准数(即最后的那个数),其二便是特殊的情况我们该如何去处理。第一个问题我发现我们可以去寻找所有数的最大公约数,我们不需要比较C(2,n)次,我们只需要把任何相邻的gcd取出来即可(具体解释大家写个样例就明白了),特殊情况就是找不到gcd,这种情况题中提到了,直接输出-1即可
代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1100;
int a[N];
int gcd(int m, int n)
{
return n ? gcd(n, m % n) : m;
}
int main()
{
int n;
cin >> n;
int s = 0, ans = 0;
for (int i = 0; i < n; i++)
{
cin >> a[i];
s = gcd(s, a[i]);
}
for (int i = 0; i < n; i++)
{
a[i] /= s;
while (a[i] % 2 == 0)
a[i] /= 2, ans++;
while (a[i] % 3 == 0)
a[i] /= 3, ans++;
if (a[i] != 1)
{
cout << -1 << " ";
return 0;
}
}
cout << ans << "\n";
return 0;
}