题目链接: 2015-2016 Northwestern European Regional Contest (NWERC 2015) E. Elementary Math
题意: 给定n, 以及n对(a, b), 每对(a, b) 均有三个操作(a*b, a+b, a-b). 给每一对选择一个操作使得任意两对的计算结果均不相同.
解析:
求离散化后,建边(将(a,b)与其三个操作计算得到的res进行连边, 即求最大匹配数,匈牙利算法n*m求解.
- 图解:
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a; i<=b; ++i)
#define mp make_pair
#define pb push_back
#define ms(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int>vi;
const int maxn = 1e4+7;
int n;
/**前向星建立边长**/
struct Edge{
int to;
int next;
}e[maxn*3];
int first[maxn], len;
void adde(int u, int v){
e[len].to = v;
e[len].next = first[u];
first[u] = len;
len++;
return ;
}
/*******/
int cnt=0;
map<ll, int>mark; //标记数离散化后的下标 inx
ll v[5*maxn]; // 离散化后的下标inx对应的数
struct node{ //保存数
ll a, b;
}p[maxn];
/*** 将(a, b) 与对应三个操作得到的result对应的离散化后的下标 连边 ***/
void build(ll a, ll inx){
if(!mark[a]){
v[cnt] = a;
mark[a] = cnt;
adde(inx, cnt);
adde(cnt, inx);
cnt++;
} else{
adde(inx, mark[a]);
adde(mark[a], inx);
}
}
/*******匈牙利算法求最大匹配板子,时间复杂度 n*m ************/
bool vis[5*maxn];
int link[5*maxn];
bool find(int u){
for(int i=first[u]; ~i; i=e[i].next){
int v = e[i].to;
if(!vis[v]){
vis[v] = true;
if(link[v] == -1 || find(link[v])){
link[v] = u;
return true;
}
}
}
return false;
}
bool MaxMatch(){
int ans=0;
rep(i, n+1, cnt-1){
ms(vis, false);
if(find(i)) ans++;
}
if(ans==n) return true;
else return false;
}
/*******输出*********/
void print(int u){
ll res = v[link[u]];
ll a = p[u].a;
ll b = p[u].b;
if( a * b == res){
printf("%lld * %lld = %lld\n", a, b, res);
} else if(a+b == res){
printf("%lld + %lld = %lld\n", a, b, res);
} else{
printf("%lld - %lld = %lld\n", a, b, res);
}
return ;
}
void init(){
ms(link, -1);
ms(first, -1);
cnt=n+1;
len=1;
}
int main(){
// freopen("in.txt", "r", stdin);
scanf("%d", &n);
mark.clear();
rep(i,1,n){
scanf("%lld %lld", &p[i].a, &p[i].b);
ll t1 = p[i].a * p[i].b;
ll t2 = p[i].a + p[i].b;
ll t3 = p[i].a - p[i].b;
build(t1, i);
if(t2!=t1){
build(t2, i);
}
if(t3!=t2 && t3!=t1){
build(t3, i);
}
}
if(MaxMatch()){
rep(i, 1, n){
print(i);
}
} else {
printf("impossible\n");
}
return 0;
}

本文针对2015-2016年 Northwestern European Regional Contest 的 E 题 Elementary Math 提供了解题思路及代码实现。通过离散化、构建图并运用匈牙利算法求解最大匹配问题,确保每对数值通过指定运算获得不同结果。

381

被折叠的 条评论
为什么被折叠?



