文章目录
牛客周赛 Round 59(思维、构造、数论)
E题,对于对角线的处理,常用。
F题,范德蒙恒等式推论的应用。
A. TD
简单数学题。
#include<bits/stdc++.h>
using namespace std;
int main(){
double n, m;
cin >> n >> m;
double res = n / m;
printf("%.10lf", res); // 注意精度
return 0;
}
B. 你好,这里是牛客竞赛
判断四个模式串是否为输入字符串的前缀即可。
#include<bits/stdc++.h>
using namespace std;
bool is_prefix(const string& A, const string& B){ // 判断B是否为A的前缀
return A.find(B) == 0; // str.find() 返回首次匹配的下标,没找到返回str.npos
}
int main(){
map<string, string> mp;
mp["https://www.nowcoder.com"] = "Nowcoder";
mp["www.nowcoder.com"] = "Nowcoder";
mp["https://ac.nowcoder.com"] = "Ac";
mp["ac.nowcoder.com"] = "Ac";
int ncase;
cin >> ncase;
while(ncase--){
string s;
cin >> s;
int is_find = 0;
for(auto x : mp){
if(is_prefix(s, x.first)){
is_find = 1;
cout << x.second << endl;
break;
}
}
if(!is_find) cout << "No" << endl;
}
return 0;
}
C. 逆序数(思维)
通过简单思考,一个序列A,任选两个元素,共有 |A| * (|A|-1)/ 2 种选择。(|A| 表示A序列中元素的个数)
对于任选的Ai 和 Aj,要么其在 A 中为逆序对,要么在 A’ 中为逆序对。(设A序列的逆序序列为A’)
综上,A 和 A’ 中逆序对的和为 |A| * (|A|-1)/ 2。
在已知A的逆序对个数和元素个数时,可以计算出A’ 中逆序对的个数。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main(){
ll n, k;
cin >> n >> k;
ll res = n * (n-1) / 2 - k; // 注意数据范围
cout << res << endl;
return 0;
}
D. 构造mex(构造)
一点点细节的构造题。
根据 k 与 n 的大小关系进行了分类,具体看代码吧。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
void print_yes(int k, int is_end){
cout << "YES" << endl;
for(int i = 0; i < k; i++){
cout << (i == 0 ? "" : " ") << i;
}
if(is_end) cout << "\n";
}
int main(){
int ncase;
cin >> ncase;
while(ncase--){
ll s, n, k;
cin >> s >> n >> k;
if(k == 0){
if(s >= n){
cout << "YES" << endl;
int sum = s - n;
for(int i = 1; i < n; i++) cout << "1 ";
cout << sum + 1 << endl;
}
else cout << "NO" << endl;
}
else if(k == 1 && s == 1) cout << "NO" << endl;
else if(k > n) cout << "NO" << endl;
else if(k == n){
ll sum = k * (k-1) / 2;
if(sum == s) print_yes(k, 1);
else cout << "NO" << endl;
}
else if(k+1 == n){
ll sum = k * (k-1) / 2;
if(sum + k != s && s >= sum){
print_yes(k, 0);
cout << " " << s - sum << endl;
}
else cout << "NO" << endl;
}
else { // 这是一种普遍的构造方法,上边的分类,均为当前分支不适配的特殊情况。
ll sum = k * (k-1) / 2;
if(sum > s) cout << "NO" << endl;
else if(sum + k != s){
print_yes(k, 0);
cout << " " << s - sum;
for(int i = k+2; i <= n; i++) cout << " " << 0;
cout << endl;
}
else{
print_yes(k, 0);
cout << " " << s - sum - 1 << " 1";
for(int i = k+3; i <= n; i++) cout << " " << 0;
cout << endl;
}
}
}
return 0;
}
E. 小红的X型矩阵
操作二等价于:可以在保证元素相对位置的基础上,把任意点放在矩阵中间。
X形矩阵的形状与 n 的奇偶有关。
-
主对角线:左上到右下;副对角线:右上到左下。
-
任意点(x, y) 所在的主对角线上的点都满足:(x-y+n) % n
-
任意点(x, y) 所在的福对角线上的点都满足:(x+y) % n
当 n为奇数时,任意点(x,y)需要的操作一的数量为:对角线上 0 的个数 + (全部 1 的个数为 X - 对角线上 1 的个数)
当 n为偶数时,任意点(x,y)需要的操作一的数量为:对角线上 0 的个数 + (全部 1 的个数为 X - 对角线上 1 的个数)
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
int a[maxn][maxn];
int z[maxn], f[maxn];
int main(){
int n;
cin >> n;
int sum_1 = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cin >> a[i][j];
z[(i-j+n)%n] &