acwing周赛37
1.合适的数对(枚举)
【题目链接】4296. 合适数对 - AcWing题库
【代码实现】
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
// 给定三个正整数 n,a,b,请你找到两个非负整数 x,y,使得 ax+by=n 成立。 ---> x,y 一定小于n
int main()
{
int n, a, b;
cin >> n >> a >> b;
bool flag = true;
for(int x = 0; x <= 1000; x ++)
for(int y = 0; y <= 1000; y ++)
{
if(a * x + b * y == n)
{
flag = false;
puts("YES");
cout << x << ' ' << y;
return 0;
}
}
if(flag) puts("NO");
return 0;
}
2.截断数组(前缀和; 哈希表;二分;双指针)
【题目链接】4297. 截断数组 - AcWing题库
2*10^5---->时间复杂度:O(nlongn)或者O(n)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PdgjVoUn-1644208218584)(E:\picture\1\645.png)]
【前缀和 + 二分】
时间复杂度:O(nlongn)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_set>
using namespace std;
typedef long long LL;
const int N = 2*1e5 + 10;
LL s[N];// 数值很大,开LL
LL ans ;
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i ++ )
{
int x;
cin >> x;
s[i] = s[i - 1] + x;
}
for(int i = 1; i <= n; i ++)// 枚举第一个位置
{
LL sum = s[i];
int l = i + 1, r = n;// 去找第二个位置
while(l < r)
{
int mid = (l + r) / 2;
if(s[n] - s[mid - 1] <= sum) r = mid;// 还有s3更大的区间(指针2靠左)
else l = mid + 1;
}
if(sum == s[n] - s[l - 1])
ans = max(ans, sum);
}
if(n == 1) ans = 0;
cout << ans;
}
【前缀和 + 哈希表】
上述的解法核心在于判断某一个值s1是否存在,使得s1 = s3,因此可以用哈希表来进行判断。然后判断s3中是否存在s1即可,由于s3是递减的,要使得s1最大,那么第二个指针尽可能在前面,即在对s3进行前缀和时,前面的s3的大的,即第一个满足要求的s3即为答案!(递减嘛)
时间复杂度:O(n)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_set>
using namespace std;
typedef long long LL;
const int N = 2*1e5 + 10;
LL s[N];// 数值很大,开LL
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i ++ )
{
int x;
cin >> x;
s[i] = s[i - 1] + x;
}
unordered_set<LL> hash;
hash.insert(s[1]);
for(int i = 2; i <= n; i ++)
{
LL s3 = s[n] - s[i - 1];
if(hash.count(s3))
{
cout << s3;
return 0;
}
hash.insert(s[i]);// s1: 1~i的和
}
puts("0");// 如果不存在s1 == s3, 则结果为0
}
3.搭档(贪心;匈牙利算法)
【题目链接】4298. 搭档 - AcWing题库
又是男女朋友问题——最大二分图匹配(匈牙利算法)
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int h[N], e[N], ne[N], idx;
int match[N];//匹配数组
bool st[N];//预定女友数组
int a[N], b[N];
int n1, n2;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
bool find(int x)
{
//遍历男孩喜欢的女孩子
for(int i = h[x]; i != -1; i = ne[i])
{
int j = e[i];
if(!st[j])//如果女孩j没被预定
{
st[j] = true;//预定女孩j
//如果女孩j没有男朋友,或者她原来的男朋友还有其他预定对象(还有备胎)。配对成功
if(!match[j] || find(match[j]))
{
match[j] = x;
return true;
}
}
}
//自己中意的全部都被预定了。配对失败。
return false;
}
int main()
{
memset(h, -1, sizeof h);
cin >> n1 ;
for (int i = 1; i <= n1; i ++ ) cin >> a[i];
cin >> n2 ;
for (int i = 1; i <= n2; i ++ ) cin >> b[i];
for (int i = 1; i <= n1; i ++ )
for (int j = 1; j <= n2; j ++ )
{
if(abs( a[i] - b[j] ) <= 1)
add(i, j);
}
int res = 0;
for (int i = 1; i <= n1; i ++ )
{
//因为每次模拟匹配的预定情况都是不一样的所以每轮模拟都要初始化
memset(st, 0, sizeof st);
if(find(i))
res ++;
}
cout << res;
return 0;
}
例题来源:acwing周赛第37场