2018 IEEE极限编程大赛 题解
去年742,今年72,也算一种小小的进步。
明年前30(笑
1. Drawing Rooted Binary Trees
给定一个树的中序和前序的遍历,要求输出这棵树(包括空格的)
#include <iostream>//
#include <string.h>//
#include <stdio.h>//
#include <stdlib.h>//
#include <math.h>//
#include <string.h>//
#include <vector>//STL vetor
#include <list>//STL list
#include <map>// STL map
#include <queue>// STL queue
#include <set>// STL set
#include <stack>//sTL stack
#include <bitset>//bitset
#include <algorithm>//STL
#include <numeric>//
#include <functional>//STL
#include <limits.h>//
#include <fstream>
using namespace std;
typedef int LL;
int Tr[][];
int n;
char z[];
char q[];
int D;
int w;
int DFS(int L,int R,int x,int d){
int i;
Tr[ q[x]-'a' ][]=d;
int xx=x;
// printf("%d %d %c %d xx=%d,w=%d\n",L,R,q[x],d,x,w);
if (L==R){
D=max(D,d);
Tr[q[x]-'a'][]=Tr[q[x]-'a'][]='@';
Tr[q[x]-'a'][]=w;
w++;
return x;
}
for (i=L;i<=R;i++){
if (z[i]==q[x]) break;
}
if (i!=L){
Tr[q[x]-'a'][]=q[x+];
x++;
x=DFS(L,i-,x,d+);
}else{
Tr[q[x]-'a'][]='@';
}
Tr[q[xx]-'a'][]=w;
w++;
if (i!=R){
Tr[ q[xx]-'a'][]=q[x+];
x=DFS(i+,R,x+,d+);
}else{
Tr[q[xx]-'a'][]='@';
}
return x;
}
char Out[];
int main(){ while(scanf("%s%s",z,q)!=EOF){
n=strlen(z);
D=;
w=;
DFS(,n-,,);
//printf("%d\n",D);
// for (int j=0;j<n;j++){printf("%c L=%c R=%c %d D=%d\n",q[j],Tr[ q[j]-'a' ][0], Tr[ q[j]-'a' ][1],Tr[ q[j]-'a' ][2],Tr[ q[j]-'a' ][3]); }
for (int i=;i<=D;i++){
for (int j=;j<n;j++){ Out[j]=' ';}
Out[n]=;
for (int j=;j<n;j++){
if ( Tr[ q[j]-'a' ][]==i ){
Out[ Tr[q[j]-'a' ][] ]=q[j];
}
}
printf("%s\n",Out);
}
}
return ;
}
2. Barter System
Standard input
The first line of the input is an integer N which indicates the number of given exchange rates to follow. The next N lines consists of A, B, rA,B,r triplets where A and B are the commodities and r is the exchange rate such that A = rB \ {mod}A=r⋅B (mod 998244353).
The next line contains another integer QQ which represents the number of queries. The following Q lines consists of a pair of commodities K and L.
Standard output
For each of the Q queries you need to find r such that $K = r \cdot LK=r⋅L$.
It can be shown that rr can be represented as $\frac{X}{Y}YX$, where X and Y are coprime integers and $X \ne 0 \ (\text{mod} \ 998244353)X≠0 (mod 998244353)$. For each query print $X \cdot Y^{-1} \ (\text{mod} \ 998244353)X⋅Y−1 (mod 998244353).$
If the exchange rate can not be computed using the given information, print -1
.
Constraints and notes
- $1 \leq N, Q \leq 2 \cdot 10^41≤N,Q≤2⋅104$
- $1 \leq |A|, |B| \leq 501≤∣A∣,∣B∣≤50$
- $1 \leq r < 9982443531≤r<998244353$
- All exchange rates are consistent
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std; const double EPS = 1e-;
const int INF = ;
const int LLINF = ;
const double PI = acos(-1.0); #define REP(i, a, b) for(int i = (a); i < (b); i++)
#define PER(i, a, b) for(int i = (a); i > (b); i--)
#define FOREACH(i,t) for(typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define NEED_CLOCK printf("Time: %f\n",double(clock())/CLOCKS_PER_SEC)
#define MP(x, y) make_pair(x, y)
#define PB(x) push_back(x)
#define SET(a) memset(a,-1,sizeof(a))
#define CLR(a) memset(a,0,sizeof(a));
#define MEM(a,x) memset(a,x,sizeof(a))
#define ALL(x) begin(x),end(x)
#define LL long long
#define Lson (index * 2)
#define Rson (index * 2 + 1)
#define pii pair< int, int >
#define pll pair< LL, LL >
#define MAXN 21000+5 template< class T > inline T _abs(T a) { return a >= ? a : -a; }
template< class T > inline T sqr(T a) { return a*a; }
template< class T > inline T gcd(T a, T b) { return (b) == ? (a) : gcd((b), ((a) % b)); }
template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b))*(b)); }
template< class T > inline T lowbit(T x) { return x&-x; } inline int READ() {
char ch;
while ((ch = getchar()) < || < ch);
int ans = ch - ;
while ( <= (ch = getchar()) && ch <= )
ans = (ans << ) + (ans << ) + ch - ;
return ans;
}
///************************************START**************************************///
const long long MOD = ;
int pre[MAXN];
LL dis[MAXN];
int findSet(int x) {
if (pre[x] == x)return x;
if (x < )return -;
int ths = pre[x];
int rhs = findSet(pre[x]);
if (ths >= && rhs >= )
pre[x] = rhs;
dis[x] = (dis[x] * dis[ths]) % MOD;
return rhs;
}
LL poww(LL x, LL n)
{
LL res = ;
while (n > )
{
if (n % == )
{
res = res*x;
res = res%MOD;
}
x = x*x;
x = x%MOD;
n >>= ;
}
return res;
}
LL inv(LL x) {
return poww(x, MOD - );
}
string s1, s2;
unordered_map<string, int>mp;
int main() {
int n; scanf("%d", &n);
//MEM(dis, 1);
for (int i = ; i < n+; i++){
pre[i] = i;
dis[i] = ;
}
int id = ;
while (n--) {
LL rate;
cin >> s1 >> s2 >> rate;
if (mp.find(s1)==mp.end())mp[s1] = id++;
if (mp.find(s2)==mp.end())mp[s2] = id++;
int fx = findSet(mp[s1]), fy = findSet(mp[s2]);
dis[fy] = (1ll * (dis[mp[s1]] * rate) % MOD*inv(dis[mp[s2]])) % MOD;
pre[fy] = fx;
}
int q; scanf("%d", &q);
while (q--) {
cin >> s1 >> s2;
if (s1 == s2) {
printf("1\n");
continue;
}
if (mp.find(s1) == mp.end() || mp.find(s2) == mp.end()) {
printf("-1\n");
continue;
}
int fx = findSet(mp[s1]), fy = findSet(mp[s2]);
if (fx != fy) {
printf("-1\n");
continue;
}
else {
printf("%lld\n", (dis[mp[s2]] * inv(dis[mp[s1]])) % MOD);
}
}
return ;
}
3. Troll Coder
You have found a huge treasure on an island, but the only access point to that island is a bridge guarded by a giant Troll! In order to cross the bridge, you have to guess a sequence of N bits by submitting queries. For each query, the Troll will tell you how many bits you guesses correctly until you guess the correct sequence.
Interaction
Your program must exchange information with the Troll by submitting queries and reading answers.
Note that you must flush the buffer so that the output reaches the Troll. Here we ilustrate it for several languages.
At the beginning of each test case, the Troll will give you a single integer N which will represent the length of the sequence.
To submit a query, your program should output the letter Q
followed by a space and by a binary sequence of length N with each bit separated by a space. After each query you will receive an integer denoting the number of correct bits. The last submission will be your final answer and it should start with an A
followed by a space and by a binary sequence of length N with each bit separated by a space.
Constraints and notes
- This task is NOT adaptive
- $1 \le N \le 1001≤N≤100 $
- Your program can submit at most N + 1 queries before arriving at the correct answer.
#include<iostream>
using namespace std;
int a[];
int n,cnt,tmp;
int flip(int &num){
if(num==){
num=;
return ;
}else{
num=;
return ;
}
}
int main()
{
cin>>n;
cout<<"Q ";
for(int i=;i<n-;++i){
a[i]=;
cout<<a[i]<<" ";
}
a[n-]=;
cout<<a[n-]<<endl;
cin>>cnt;
if(cnt==n){
cout<<"A ";
for(int i=;i<n-;++i){
cout<<a[i]<<" ";
}
cout<<a[n-]<<endl;
}else if(cnt==){
cout<<"A ";
for(int i=;i<n-;++i){
cout<<flip(a[i])<<" ";
}
cout<<flip(a[n-])<<endl;
}else{
for(int i=;i<n;++i){
cout<<"Q ";
for(int j=;j<n-;++j){
if(i!=j) cout<<<<" ";
else cout<<<<" ";
}
if(i!=n-) cout<<<<endl;
else cout<<<<endl;
cin>>tmp;
if(tmp>cnt){
a[i]=;
}
}
cout<<"A ";
for(int i=;i<n-;++i){
cout<<a[i]<<" ";
}
cout<<a[n-]<<endl; }
return ;
}
4. Xtreme Fake Coins
Help IBM research's puzzlemaster to verify solutions for May 2018's challenge.
There are NN coins, represented by the first NN capital letters of the English alphabet. Exactly two of them are counterfeit and have a slightly smaller weight. MM weightings using a double-pan balance scale have been performed, but they may not uniquely determine the pair of counterfeit coins.
Find all counterexamples of two pairs of coins ((a, b), (c, d)) \ (a < b, \ a \leq c, \ c < d,\ (a, b) \neq (c, d))((a,b),(c,d)) (a<b, a≤c, c<d, (a,b)≠(c,d)) whose weights are indistinguishable with respect to the MM weightings.
Standard input
The first line contains two comma separated integers, NN and MM.
The next MM lines contain two strings of disjoint subsets of the first NN English capital letters, separated by a -
sign.
There always is an equal amount of coins on both sides.
Standard output
List of lexicographically ordered counterexamples for the solution.
Each of them consists of two letters, an =
sign and then another two letters.
A counterexample is a set of two pairs that cannot be distinguished by the set of MM weightings.
Constraints and notes
- 0 \leq M \leq 100≤M≤10
- 2 \leq N \leq 262≤N≤26
- The counterexamples should be formed using only the first NN letters
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std; const double EPS = 1e-;
const int INF = ;
const int LLINF = ;
const double PI = acos(-1.0); #define REP(i, a, b) for(int i = (a); i < (b); i++)
#define PER(i, a, b) for(int i = (a); i > (b); i--)
#define FOREACH(i,t) for(typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define NEED_CLOCK printf("Time: %f\n",double(clock())/CLOCKS_PER_SEC)
#define MP(x, y) make_pair(x, y)
#define PB(x) push_back(x)
#define SET(a) memset(a,-1,sizeof(a))
#define CLR(a) memset(a,0,sizeof(a));
#define MEM(a,x) memset(a,x,sizeof(a))
#define ALL(x) begin(x),end(x)
#define LL long long
#define Lson (index * 2)
#define Rson (index * 2 + 1)
#define pii pair< int, int >
#define pll pair< LL, LL >
#define MOD ((int)1000000007)
#define MAXN 300000 template< class T > inline T _abs(T a) { return a >= ? a : -a; }
template< class T > inline T sqr(T a) { return a*a; }
template< class T > inline T gcd(T a, T b) { return (b) == ? (a) : gcd((b), ((a) % b)); }
template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b))*(b)); }
template< class T > inline T lowbit(T x) { return x&-x; } inline int READ() {
char ch;
while ((ch = getchar()) < || < ch);
int ans = ch - ;
while ( <= (ch = getchar()) && ch <= )
ans = (ans << ) + (ans << ) + ch - ;
return ans;
}
///************************************START**************************************///
string g[MAXN][];
string ans[MAXN][];
int n, m;
char c[MAXN]; vector<string>v;
void generate() {
for (int i = ; i < n; i++) {
for (int j = i + ; j < n; j++) {
string a;
a.push_back('A' + i);
a.push_back('A' + j);
v.push_back(a);
}
}
return;
} int check(int k, string s) {
int l0 = g[k][].find(s[]) == - ? : ;
int r0 = g[k][].find(s[]) == - ? : ;
int l1 = g[k][].find(s[]) == - ? : ;
int r1 = g[k][].find(s[]) == - ? : ; int left = l0 + l1, right = r0 + r1;
if (left == right)return ;
else if (left > right)return ;
else if (left < right)return ;
} int main() {
scanf("%d,%d", &n, &m);
generate(); for (int i = ; i < m; i++) {
scanf("%s", c);
int j = ;
string a, b;
for (j = ; j < strlen(c); j++) {
if (c[j] != '-') a.push_back(c[j]);
else break;
}
for (j += ; j < strlen(c); j++) {
b.push_back(c[j]);
}
g[i][] = a;
g[i][] = b;
} int cnt = ;
for (int i = ; i < v.size(); i++) {
for (int j = i + ; j < v.size(); j++) {
//cout << v[i] << " " << v[j] << endl;
int flag = ;
for (int k = ; k < m; k++) {
if (check(k, v[i]) != check(k, v[j])){
flag = ;
break;
}
}
if (flag) {
ans[cnt][] = v[i];
ans[cnt][] = v[j];
cnt++;
}
}
} for (int i = ; i < cnt; i++) {
cout << ans[i][] << '=' << ans[i][] << endl;
} return ;
}
5. Magic Spell
Write a program that gives the correct output for a legal input – to discover the correct function see the input/output examples.
Standard Input
The first line contains an integer NN. Each of the following NN lines will contain a legal string.
Standard output
Print the answer on the first line. It is guaranteed that it can be represented as a signed 6464 integer.
#include <iostream>//数据输入输出流
#include <string.h>//字符串操作函数
#include <stdio.h>//C的输入输出
#include <stdlib.h>//定义杂项函数及内存分配函数
#include <math.h>//C中的数学函数
#include <string.h>//c++中的string类 他不能用strcpy等c函数去操作
#include <vector>//STL vetor容器
#include <list>//STL list
#include <map>// STL map
#include <queue>// STL queue
#include <set>// STL set
#include <stack>//sTL stack
#include <bitset>//bitset可按位定义串//比如:bitset <1000> all;定义一个1000位的串
#include <algorithm>//STL各种算法 比如 swap sort merge max min 比较
#include <numeric>//常用数字操作 一般和algorithm搭配使用
#include <functional>//STL定义运算函数(代替运算符)
#include <limits.h>//定义各种数据类型最值常量
#include <fstream>
#include <cstring>
using namespace std;
typedef int LL;
int a[];
LL Get(char *s) {
if (strcasecmp(s, "xrtp") == ) return 0ll;
if (strcasecmp(s, "pmr") == ) return 1ll;
if (strcasecmp(s, "yep") == ) return 2ll;
if (strcasecmp(s + , "jtrr") == ) return 3ll;
if (strlen(s) == && s[] == 'g' &&s[] == 'p') return 4ll;
if (strcasecmp(s, "gobr") == ) return 5ll;
if (strlen(s) == && s[] == 'd' && s[] == 'o') return 6ll;
if (strcasecmp(s, "drbrm") == ) return 7ll;
if (strcasecmp(s, "rohjy") == ) return 8ll;
if (strcasecmp(s, "momr") == ) return 9ll;
if (strcasecmp(s, "yrm") == ) return 10ll;
if (strcasecmp(s + , "rbrm") == ) return 11ll;
if (strlen(s) == && s[] == 'y' &&s[] == 'e'&&s[] == 'r') return 12ll;
if (strlen(s) == && s[] == 'j' &&s[] == 'o'&&s[] == 't') return 13ll;
if (strlen(s) == && s[] == 'g' &&s[] == 'p'&&s[] == 't') return 14ll;
if (strlen(s) == && s[] == 'g' &&s[] == 'o'&&s[] == 'g') return 15ll;
return -;
}
char s[];
char ss[];
string ns;
long long x, ans;
int n;
vector<vector<string> > v;
int main() {
/*scanf("%d", &n);
ans = 1ll;
for (int i = 0; i < n; i++) {
getline(cin, ns);
x = 0ll;
int Len = 0;
int j, cnt = 0;
puts(ss);
x = x * 16ll + Get(ss);
Len += strlen(ss); ans = ans*x;
}
printf("%lld\n", ans);
return 0;*/ int n; cin >> n;
ans = 1ll;
while (n--) {
vector<string> vt;
while () {
string s;
cin >> s;
vt.push_back(s);
if (getchar() == '\n') break;
}
v.push_back(vt);
}
for (int i = ; i < v.size();i++) {
x = 0ll;
for (int j = ; j < v[i].size(); j++) {
for (int k = ; k < v[i][j].size(); k++) {
ss[k] = v[i][j][k];
}
ss[v[i][j].size()] = '\0';
x = x * 16ll + Get(ss);
}
ans *= x;
}
printf("%lld\n", ans);
return ;
}
6. Bear Sums
Mitsos the bear is challenging his brother Vangelis with a mathematical task. Mitsos provides a list of integers LL and another integer value SS, then he asks Vangelis to check if there are any two items in the list LL whose sum is equal to the integer SS.
Since Vangelis is a confident engineer, he decided to write a program that would do all the computations for him and skip the trouble of thinking. Your task is to help Vangelis write a program that reads the input list LL and the integer SS and produces either the solution to the problem or provides an error message when there is no solution available.
Standard input
On the first line there will be an integer number TT (representing the number of test cases) followed by 22 input lines for each test case:
- On the first line of each test case, there will be 22 integers SS and EE, where SS is the expected sum and EE is the number of elements in the list.
- On the second line, there will be EE integers separated by a space. Each integer represents an element of the list LL. The elements are not sorted in any way and some could have the same value. In cases where the number EE is 00, the second line will be empty.
All values for the elements of list LL will be in the same range as the value SS.
Standard output
For each test case you will have to write one line that contains:
- If there is an unique solution: Write two elements, xx and yy of the list LL, separated by a single space, such that x + y = Sx+y=S and x \le yx≤y.
- If there are multiple solutions: Pick the first complete pair that appears on the list and provides the correct sum. Print the two list elements forming this pair in increasing order, as above.
- If there is no solution: Print the error message
!OK
.
Constraints and notes
- 1 \leq T \leq 1\ 0001≤T≤1 000
- -10^6 < S < 10^6−106<S<106
- 0 \leq E \leq 2 \cdot 10^40≤E≤2⋅104
- The sum of values of EE is at most 10^7107
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std; const double EPS = 1e-;
const int INF = ;
const int LLINF = ;
const double PI = acos(-1.0); #define REP(i, a, b) for(int i = (a); i < (b); i++)
#define PER(i, a, b) for(int i = (a); i > (b); i--)
#define FOREACH(i,t) for(typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define NEED_CLOCK printf("Time: %f\n",double(clock())/CLOCKS_PER_SEC)
#define MP(x, y) make_pair(x, y)
#define PB(x) push_back(x)
#define SET(a) memset(a,-1,sizeof(a))
#define CLR(a) memset(a,0,sizeof(a));
#define MEM(a,x) memset(a,x,sizeof(a))
#define ALL(x) begin(x),end(x)
#define LL long long
#define Lson (index * 2)
#define Rson (index * 2 + 1)
#define pii pair< int, int >
#define pll pair< LL, LL >
#define MOD ((int)1000000007)
#define MAXN 20000+10 template< class T > inline T _abs(T a) { return a >= ? a : -a; }
template< class T > inline T sqr(T a) { return a*a; }
template< class T > inline T gcd(T a, T b) { return (b) == ? (a) : gcd((b), ((a) % b)); }
template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b))*(b)); }
template< class T > inline T lowbit(T x) { return x&-x; } inline int READ() {
char ch;
while ((ch = getchar()) < || < ch);
int ans = ch - ;
while ( <= (ch = getchar()) && ch <= )
ans = (ans << ) + (ans << ) + ch - ;
return ans;
}
///************************************START**************************************///
int ini[MAXN];
struct node{
int id, val;
bool operator < (const node & rhs) const {
return val < rhs.val || (val == rhs.val&&id < rhs.id);
}
}a[MAXN]; struct fi{
int p1, p2;
bool operator < (const fi &rhs)const {
return p2 < rhs.p2 || (p2 == rhs.p2&&p1 < rhs.p1);
}
}ans[MAXN]; int lowbou(int l, int r, int tar){
while (l <= r) {
int mid = (l + r) / ;
if (a[mid].val < tar) l = mid + ;
else r = mid - ;
}
return l;
} int main() {
int T; scanf("%d", &T);
while (T--) {
int sum, e; scanf("%d%d", &sum, &e);
if (e == ) {
printf("!OK\n");
continue;
}
for (int i = ; i < e; i++) {
a[i].id = i;
scanf("%d", &a[i].val);
ini[i] = a[i].val;
} sort(a, a + e);
int cnt = ;
for (int i = ; i < e; i++) {
int need = sum - a[i].val;
int pos = lowbou(, e - , need);
if (pos != e && a[pos].val == need && a[pos].id != a[i].id) {
ans[cnt] = { a[i].id,a[pos].id };
if (ans[cnt].p1 > ans[cnt].p2){
swap(ans[cnt].p1, ans[cnt].p2);
}
cnt++;
}
}
if (cnt == ) {
printf("!OK\n");
continue;
} sort(ans, ans + cnt);
//cout << ans[0].p1 << " " << ans[0].p2 << endl;
if (ini[ans[].p1] > ini[ans[].p2])
swap(ini[ans[].p1], ini[ans[].p2]);
printf("%d %d\n", ini[ans[].p1], ini[ans[].p2]);
//cout << endl;
}
return ;
}
7. Lemons
If life gives you lemon trees, make sure they have enough water!
Pantelis owns a small field of lemon trees on the foot of the Troodos mountain. He has chosen to grow his trees at this location mainly because Troodos mountain has a continuous source of fresh water for watering the trees. The water captured on the slopes, at high altitudes, flows under gravity via the stream and it is stored and distributed through an underground network of water pipes and water pumps.
Unfortunately, earlier this morning, Pantelis noticed that the flow of water from the water pump in his field is significantly reduced, and this will severely affect this season’s crop of lemons. Watering lemon trees is tricky. Too little or too much water and the tree will die. You should never let a lemon tree dry out completely for more than a day. Pantelis suspects that one of the water pumps on the channel has malfunctioned causing the water shortage. He needs to immediately determine which pump malfunctioned, notify maintenance in order to get it fixed and re-establish the regular water flow to his trees. Since the water runs in underground pipes he has no way of knowing if the flow is reduced in the pipes. He needs to climb the mountain and methodically check each of the water pumps for shortage in water levels in order to figure out which one is damaged.
There are NN water pumps evenly set apart along the network, with the first one (last in the flow line) being located at Pantelis’s field. Pantelis knows that his pump is working properly. All the pumps ranging from the damaged pump down to Pantelis’s pump are having water shortage. It takes Pantelis MM minutes to get to the next pump on the mountain (uphill or downhill) and SS minutes to check the pump for water shortage.
Pantelis needs to minimize the time needed to find the damaged water pump. Therefore, your program should find a plan to minimize the time to find the damaged water pump in the worst case scenario.
Standard input
The input consists of three space-separated integers NN, MM and SS. NN is the total number of water pumps on the network. Pantelis pump is number 11. MM is the time it takes Pantelis to travel to the next pump of the network (uphill or downhill), and SS is the number of minutes it takes to check if a water pump is having water shortage.
Standard output
The output consists of a single integer. The minimum worst-case time to find the damaged water pump.
Constraints and notes
- 2 \leq N \leq 10^42≤N≤104
- 0 \leq M \leq 1\ 0000≤M≤1 000
- 0 \leq S \leq 1\ 0000≤S≤1 000
#include <iostream>//数据输入输出流
#include <string.h>//字符串操作函数
#include <stdio.h>//C的输入输出
#include <stdlib.h>//定义杂项函数及内存分配函数
#include <math.h>//C中的数学函数
#include <string.h>//c++中的string类 他不能用strcpy等c函数去操作
#include <vector>//STL vetor容器
#include <list>//STL list
#include <map>// STL map
#include <queue>// STL queue
#include <set>// STL set
#include <stack>//sTL stack
#include <bitset>//bitset可按位定义串//比如:bitset <1000> all;定义一个1000位的串
#include <algorithm>//STL各种算法 比如 swap sort merge max min 比较
#include <numeric>//常用数字操作 一般和algorithm搭配使用
#include <functional>//STL定义运算函数(代替运算符)
#include<limits.h>//定义各种数据类型最值常量
#include <fstream>
using namespace std;
typedef int LL;
int main(){
int n,m,s;
scanf("%d%d%d",&n,&m,&s);
int now=;
int End=n;
int Wgo=m;
int Wdo=s;
int step;
int ans=;
while(now!=End){
step = (now+End)/ + (now+End)%;
ans+=(step-now)*Wgo+Wdo;
now=step;
}
printf("%d\n",ans);
return ;
}
8. Make Distinct
You are given an array of NN integers, AA. An operation involves taking a number from the array and either adding or subtracting 11 from it. What is the minimum number of operations to make AA have only distinct elements.
Standard input
The first line contains an integer NN.
The second line contains NN elements, representing AA.
Standard output
Print the answer on the first line.
Constraints and notes
- 1 \leq N \leq 2 \cdot 10^51≤N≤2⋅105
- 1 \leq A_i \leq N1≤Ai≤N for all valid ii
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std; const double EPS = 1e-;
const int INF = ;
const int LLINF = ;
const double PI = acos(-1.0); #define REP(i, a, b) for(int i = (a); i < (b); i++)
#define PER(i, a, b) for(int i = (a); i > (b); i--)
#define FOREACH(i,t) for(typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define NEED_CLOCK printf("Time: %f\MAXN",double(clock())/CLOCKS_PER_SEC)
#define MP(x, y) make_pair(x, y)
#define PB(x) push_back(x)
#define SET(a) memset(a,-1,sizeof(a))
#define CLR(a) memset(a,0,sizeof(a));
#define MEM(a,x) memset(a,x,sizeof(a))
#define ALL(x) begin(x),end(x)
#define LL long long
#define Lson (index * 2)
#define Rson (index * 2 + 1)
#define pii pair< int, int >
#define pll pair< LL, LL >
#define MOD ((int)1000000007)
#define MAXN 200000+5 template< class T > inline T _abs(T a) { return a >= ? a : -a; }
template< class T > inline T sqr(T a) { return a*a; }
template< class T > inline T gcd(T a, T b) { return (b) == ? (a) : gcd((b), ((a) % b)); }
template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b))*(b)); }
template< class T > inline T lowbit(T x) { return x&-x; } inline int READ() {
char ch;
while ((ch = getchar()) < || < ch);
int ans = ch - ;
while ( <= (ch = getchar()) && ch <= )
ans = (ans << ) + (ans << ) + ch - ;
return ans;
}
///************************************START**************************************///
int n, now;
int a[MAXN], root[MAXN];
int L[MAXN], R[MAXN], tot[MAXN]; struct Ltree {
int cnt;
int l[MAXN], r[MAXN];
int v[MAXN], Size[MAXN], d[MAXN];
int merge(int x, int y) {
if (x == || y == )return x + y;
if (v[x] < v[y])swap(x, y);
r[x] = merge(r[x], y);
Size[x] = Size[l[x]] + Size[r[x]] + ;
if (d[r[x]] > d[l[x]])swap(l[x], r[x]);
d[x] = d[r[x]] + ;
return x;
}
inline int top(int x) {
return v[x];
}
inline int size(int x) {
return Size[x];
}
inline void pop(int &x) {
x = merge(l[x], r[x]);
}
inline int new_heap(int x) {
v[++cnt] = x;
Size[cnt] = ;
l[cnt] = r[cnt] = d[cnt] = ;
return cnt;
}
}h;
int check(LL ans) {
while (ans) { int x = ans% ; ans /= ; }
return ;
}
int main() {
LL ans = ;
scanf("%d", &n);
for (int i = ; i <= n; i++) {
scanf("%d", &a[i]);
}
sort(a + , a + n + );
for (int i = ; i <= n; i++) {
a[i] -= i;
}
for (int i = ; i <= n; i++) {
now++;
root[now] = h.new_heap(a[i]);
L[now] = i;
R[now] = i;
tot[now] = ;
while (now > ) {
if (h.top(root[now - ]) <= h.top(root[now]))break;
else {
now--;
root[now] = h.merge(root[now], root[now + ]);
tot[now] += tot[now + ];
R[now] = R[now + ];
while (h.size(root[now]) * > tot[now] + )
h.pop(root[now]);
}
}
}
for (int i = ; i <= now; i++) {
int t = h.top(root[i]);
for (int j = L[i]; j <= R[i]; j++) {
if(check(ans))
ans += abs(a[j] - t);
}
}
cout << ans << endl;
return ;
}
9. Telescope Scheduling
Memory limit: 256 MB
Joe and his friends want to observe the stars tonight using a unique telescope. Joe is an astronomy student and has a list of each of the stars that will be visible in the sky. Each star appears inside a certain time window with the possibility of multiple stars to overlap, so the group assigned a value to each star indicating the desirability of observing it.
The input consists on a list LL of time intervals in which the stars will be available for observation. Each interval i \in Li∈L consists of the following elements:
- a start time S_iSi after which the star will be available for observation;
- a finish time F_iFi after which the star will no longer be available;
- a positive integer D_iDi indicating the desirability to see the ii-th star.
In order to satisfy the desirability of seeing the ii-th star, the observations must be performed by the telescope for the entire time period from S_iSi to F_iFi (inclusive). Thus, two stars, ii and jj, are not simultaneously observable (i.e. they conflict) if the time interval [S_i,F_i][Si,Fi] intersects the time interval [S_j,F_j][Sj,Fj]. Given the list LL of time intervals of availability of the stars in the sky, the optimization problem is to schedule the observations in a non-conflicting way so as to maximize the total desirability of the observations that are included in the schedule.
Standard input
The first line of the input contains a positive integer NN indicating the number of stars.
Each of the following ii lines, 1 \leq i \leq N1≤i≤N, indicates the start (S_iSi) and finish (F_iFi) times of each star together with the desirability D_iDi of seeing that star.
Standard output
Print the sum of the desirability of the stars included in the schedule on the first line.
Constraints and notes
- 1 \leq N \leq 10^41≤N≤104
- 0 \leq S_i,F_i \leq 1\ 0000≤Si,Fi≤1 000
- 1 \leq D_i \leq 5\ 0001≤Di≤5 000
#include <iostream>//数据输入输出流
#include <string.h>//字符串操作函数
#include <stdio.h>//C的输入输出
#include <stdlib.h>//定义杂项函数及内存分配函数
#include <math.h>//C中的数学函数
#include <string.h>//c++中的string类 他不能用strcpy等c函数去操作
#include <vector>//STL vetor容器
#include <list>//STL list
#include <map>// STL map
#include <queue>// STL queue
#include <set>// STL set
#include <stack>//sTL stack
#include <bitset>//bitset可按位定义串//比如:bitset <1000> all;定义一个1000位的串
#include <algorithm>//STL各种算法 比如 swap sort merge max min 比较
#include <numeric>//常用数字操作 一般和algorithm搭配使用
#include <functional>//STL定义运算函数(代替运算符)
#include<limits.h>//定义各种数据类型最值常量
#include <fstream>
using namespace std;
typedef int LL;
int dp[][]; int main(){
int n,x,y,z;
scanf("%d",&n);
memset(dp,,sizeof(dp));
int m=;
for (int i=;i<n;i++){
scanf("%d%d%d",&x,&y,&z);
dp[x][y]=max(dp[x][y],z);
//m=max(m,y);
}
int R;
for (int len=;len<=m+;len++){
for (int L=;L<=m-len+;L++){
R=L+len-;
for (int k=L;k<R;k++){
dp[L][R]=max(dp[L][R],dp[L][k]+dp[k+][R]);
}
}
}
printf("%d\n",dp[][m]);
return ;
}
10. Xplore
Memory limit: 256 MB
Click here to learn more about Xplore API
The IEEE Xplore Application Programming Interface (API) is an efficient data delivery vehicle for content indexing/discovery as well as text and data mining of IEEE metadata content of academic publications. Loading a database/repository using the content delivered by the IEEE API can be subsequently used to draw domain/subject relationships, data analytics, and various other use cases for researchers. To learn more about the IEEE Xplore API please visit developer.ieee.org and register for an API key. All participants of the IEEEXtreme 12.0 competition will have access to the IEEE API during and after the competition, for a limited period of time, to discover its research utility potential.
A useful metric commonly associated with academic publishing is the h-index. An author with an index of hh has published hh papers each of which has been cited in other papers at least hh times.
For this challenge, write a program that reads a set of NN entries from the Xplore database, in a JSON format, and prints ALL author names followed by the their h-index. The authors should be raked by h-index and by alphabetical order in case of an h-indextie.
Standard input
The input will consist of an integer NN, followed by NN lines with a single article entry in each line in a JSON format.
Each entry will follow a format described in the Xplore API website: developer.ieee.org/docs/read/Metadata_API_responses
Standard output
Print the authors ranked by their h-index followed by a space and by the h-index itself. The authors should be ranked alphabetically if there are ties.
Constraints and notes
- 2 \leq N \leq 100002≤N≤10000
import json
class data:
def __init__(self, name, num):
self.name = name
self.num = num n=int(input())
l=list()
while n>0:
s=str(input())
json_data=json.loads(s)
l.append(json_data)
n=n-1 name=list()
cite_num=list()
for i in range(len(l)):
l2=l[i]['authors']['authors']
for j in range(len(l2)):
name.append(l2[j]['full_name'])
cite_num.append(l[i]['citing_paper_count']) d={}
for i in range(len(name)):
if name[i] in d:
l=d[name[i]]
l.append(cite_num[i])
d[name[i]]=l
else:
l=list()
l.append(cite_num[i])
d[name[i]]=l d2={}
for key in d:
l3=d[key]
l3.sort(reverse=True)
h_index=0
for i in range(len(l3)):
if l3[i]>=i+1:
h_index=h_index+1
d2[key]=-1*h_index tmp=[]
for key in d2:
tmp.append(data(key,d2[key]))
tmp=sorted(tmp,key=lambda x:(x.num,x.name))
for i in range(len(tmp)):
print(tmp[i].name+" "+str(-1*tmp[i].num))
11. Tree Fun
Memory limit: 256 MB
You are given a tree with NN nodes, each node has a score which is initially 00.
The input contains the structure of the tree as well as a list of MM operations. Each operation identifies a pair of nodes (AA, BB) and a value KK. With each operation the value of each node in the path between AA an BB is increased by KK, including the starting and ending nodes.
After performing all the operations in the input, print the maximum score in the tree.
Standard Input
The first line of the input contains two integers: the number of nodes NN, and the number of operations MM.
The next N-1N−1 lines contain 22 integers U_iUi, V_iVi denoting an edge between U_iUi and V_iVi.
The following MM lines contain three integers A_iAi, B_iBi, K_iKi representing the starting node, ending node, and score to add along the path.
Standard Output
A single integer representing the maximum score in the tree.
Constraints and notes
- 1 \leq N, M \leq 10^51≤N,M≤105
- 0 \leq U_i, V_i, A_i, B_i < N0≤Ui,Vi,Ai,Bi<N
- 1 \leq K_i \leq 1\ 0001≤Ki≤1 000
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + , M = , mod = 1e9 + , inf = 0x3f3f3f3f;
typedef long long ll; int head[N], t = , sz, v[N], pos[N], belong[N], siz[N], vis[N], n, m, p, C[N], deep[N], fa[N][];
struct data { int to, next; }e[N * ];
//树链
void add(int u, int v) { e[t].to = v; e[t].next = head[u]; head[u] = t++; }
void dfs1(int x) {
siz[x] = vis[x] = ;
for (int i = ; i <= ; i++) {
if (deep[x] < ( << i)) break;
fa[x][i] = fa[fa[x][i - ]][i - ];
}
for (int i = head[x]; i; i = e[i].next) {
if (vis[e[i].to]) continue;
deep[e[i].to] = deep[x] + ;
fa[e[i].to][] = x;
dfs1(e[i].to);
siz[x] += siz[e[i].to];
}
}
void dfs2(int x, int chain) {
int k = ;
sz++;
pos[x] = sz;
belong[x] = chain;
for (int i = head[x]; i; i = e[i].next)
if (deep[x] < deep[e[i].to] && siz[k] < siz[e[i].to]) k = e[i].to;
if (k == )return;
dfs2(k, chain);
for (int i = head[x]; i; i = e[i].next)
if (deep[x] < deep[e[i].to] && k != e[i].to) dfs2(e[i].to, e[i].to);
}
int lca(int x, int y) {
if (deep[x] < deep[y]) swap(x, y);
int t = deep[x] - deep[y];
for (int i = ; i <= ; i++)
if (t&( << i)) x = fa[x][i];
for (int i = ; i >= ; i--)
if (fa[x][i] != fa[y][i]) {
x = fa[x][i];
y = fa[y][i];
}
if (x == y) return x;
return fa[x][];
}
//数据结构
void update(int x, int c) {
while (x <= n) {
C[x] += c;
x += x&-x;
}
}
int ask(int x) {
int sum = ;
while (x > ) {
sum += C[x];
x -= x&-x;
}
return sum;
}
void solvechange(int x, int f, int c) {
while (belong[x] != belong[f]) {
update(pos[belong[x]], c);
update(pos[x] + , -c);
x = fa[belong[x]][];
}
update(pos[f], c);
update(pos[x] + , -c);
}
void scan() {
for (int i = ; i < n; i++) {
int x, y;
scanf("%d%d", &x, &y);
x++, y++;
add(x, y); add(y, x);
}
dfs1();
dfs2(, ); for (int i = ; i <= n; i++) {
update(pos[i], v[i]);
update(pos[i] + , -v[i]);
}
char ch[];
int x, y, c;
for (int i = ; i <= p; i++) {
scanf("%d%d%d", &x, &y, &c);
x++, y++;
int t = lca(x, y);
solvechange(x, t, c);
solvechange(y, t, c);
solvechange(t, t, -c);
}
int ans = -0x3f3f3f3f;
for (int i = ; i <= n; i++) {
ans = max(ans, ask(pos[i]));
}
printf("%d", ans);
}
void init() {
memset(head, , sizeof(head));
t = ;
sz = ;
memset(fa, , sizeof(fa));
memset(deep, , sizeof(deep));
memset(v, , sizeof(v));
memset(vis, , sizeof(vis));
memset(C, , sizeof(C));
memset(pos, , sizeof(pos));
}
int main() {
while (scanf("%d%d", &n, &p) != EOF) {
init();
scan();
}
return ;
}
12. Bit Soccer
Memory limit: 256 MB
Peredo is a computer scientist who loves soccer. His favorite soccer player is Paolo Guerrero, one of the best Peruvian players, and his favorite team is the Brazilian national team.
He has a very large database of players with videos, photos, and many statistics related to their performance in hundreds of games. He uses his database to compute a binary performance index that tracks the players' abilities across 40 possible game metrics.
The performance index represents all possible soccer abilities of each player with a 00 for a lack of ability in a given game metric and a 11 for perfect ability, with no fractions in between 00 and 11.
Based on these numbers, Peredo created a simulation game that takes the performance indices and combines multiple players to form a team performance index.
The team performance index is such that if a single player has a 11 in a given metric then the team performance index also has a 11 in that metric.
You are given a list of players in your roster represented by their performance indices in decimal format and your tasks is to combine a subset from your roster to form your starting team and to obtain a specific team performance index. There is no limit to the number of players that can form the starting team.
As an example, simplifying with just 4 game metrics, if we have two players on our starting team with performance indices 55 (0101)
and 33 (0011)
the resulting team performance index will be 77 (0111)
.
Standard input
The first line of the input contains an integer NN denoting the number of player available in your roster. The second line contains NN integers P_iPi, denoting the performance indices of each player. The third line contains an integer QQ, denoting the number of queries, and each of the next QQ lines contains an integer GG that represents the goal team performance index.
Standard output
For each query, print YES
if it is possible to select a starting team from the roster and obtain the team performance index GG, otherwise print NO
.
Constraints and notes
- 1 \leq N \leq 10^51≤N≤105
- 1 \leq Q \leq 201≤Q≤20
- 1 \leq P_i, G \leq 2^{40}-11≤Pi,G≤240−1
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std; const double EPS = 1e-;
const int INF = ;
const int LLINF = ;
const double PI = acos(-1.0); #define REP(i, a, b) for(int i = (a); i < (b); i++)
#define PER(i, a, b) for(int i = (a); i > (b); i--)
#define FOREACH(i,t) for(typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define NEED_CLOCK printf("Time: %f\n",double(clock())/CLOCKS_PER_SEC)
#define MP(x, y) make_pair(x, y)
#define PB(x) push_back(x)
#define SET(a) memset(a,-1,sizeof(a))
#define CLR(a) memset(a,0,sizeof(a));
#define MEM(a,x) memset(a,x,sizeof(a))
#define ALL(x) begin(x),end(x)
#define LL long long
#define Lson (index * 2)
#define Rson (index * 2 + 1)
#define pii pair< int, int >
#define pll pair< LL, LL >
#define MOD ((int)1000000007)
#define MAXN 100005 template< class T > inline T _abs(T a) { return a >= ? a : -a; }
template< class T > inline T sqr(T a) { return a*a; }
template< class T > inline T gcd(T a, T b) { return (b) == ? (a) : gcd((b), ((a) % b)); }
template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b))*(b)); }
template< class T > inline T lowbit(T x) { return x&-x; } inline int READ() {
char ch;
while ((ch = getchar()) < || < ch);
int ans = ch - ;
while ( <= (ch = getchar()) && ch <= )
ans = (ans << ) + (ans << ) + ch - ;
return ans;
}
///************************************START**************************************///
LL a[MAXN];
int main() {
int n; scanf("%d", &n);
for (int i = ; i < n; i++) {
scanf("%lld", &a[i]);
}
int q; scanf("%d", &q);
for (int i = ; i < q; i++) {
LL g; scanf("%lld", &g);
LL now = ;
for (int j = ; j < n; j++) {
//cout << (a[j] & g) << endl;
if ((a[j] & g) == a[j]) {
now = now | a[j];
}
}
if (now == g) printf("YES\n");
else printf("NO\n");
}
return ;
}
2018 IEEE极限编程大赛 题解的更多相关文章
- IEEEXtreme 极限编程大赛题解
这是 meelo 原创的 IEEEXtreme极限编程大赛题解 IEEEXtreme全球极限编程挑战赛,是由IEEE主办,IEEE学生分会组织承办.IEEE会员参与指导和监督的.IEEE学生会员以团队 ...
- 爬格子呀--IEEE极限编程大赛留念
10.14,坐标:电子科技大学 24h,不间断的编程,感觉还是很爽的. 排名一般,但是这是开始,未来还很远. 题目举例1: 广袤的非洲大草原上,狮子居住在一个个的网格里,他们的势力范围会以曼哈顿路程的 ...
- 美团2018年CodeM大赛-初赛B轮 B 配送(最短路)
美团2018年CodeM大赛-初赛B轮 B 配送 题意 题解 对于每个任务,只要从上个任务的终点出发即可. 时间.地点很少,可以算出每个地点-时间的最小花费. 以题目描述的起点终点起始结束时间建图,很 ...
- 2018湘潭邀请赛 AFK题解 其他待补...
A.HDU6276:Easy h-index Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/O ...
- 2017年中国大学生程序设计竞赛-中南地区赛暨第八届湘潭市大学生计算机程序设计大赛题解&源码(A.高斯消元,D,模拟,E,前缀和,F,LCS,H,Prim算法,I,胡搞,J,树状数组)
A------------------------------------------------------------------------------------ 题目链接:http://20 ...
- Tsinghua 2018 DSA PA2简要题解
反正没时间写,先把简要题解(嘴巴A题)都给他写了记录一下. upd:任务倒是完成了,我也自闭了. CST2018 2-1 Meteorites: 乘法版的石子合并,堆 + 高精度. 写起来有点烦貌似. ...
- IEEE Bigger系列题解
Bigger系列题解 Bigger Python 坑点在于要高精度以及表达式求值,用java写可以很容易避免高精度问题 然后这道题就可以AC了 代码 import java.io.*; import ...
- 华东交通大学2017年ACM双基程序设计大赛题解
简单题 Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other) Total Submissio ...
- Tsinghua 2018 DSA PA3简要题解
CST2018 3-1-1 Sum (15%) 简单的线段树,单点修改,区间求和. 很简单. CST2018 3-1-2 Max (20%) 高级的线段树. 维护区间最大和,区间和,左边最大和,右边最 ...
随机推荐
- 基于MXNet的im2rec.py的debug
1.im2rec.py调试错误:multiprocessing not available, fall back to single threaded encoding imread 经过查找发现是程 ...
- hive执行计划简单分析
原始SQL: select a2.ISSUE_CODE as ISSUE_CODE, a2.FZQDM as FZQDM, a2.FZQLB as FZQLB, a2.FJJDM as FJJDM, ...
- python 分析慢查询日志生成报告
python分析Mysql慢查询.通过Python调用开源分析工具pt-query-digest生成json结果,Python脚本解析json生成html报告. #!/usr/bin/env pyth ...
- 如何在 CentOS 7 / RHEL 7 终端服务器上安装 KVM
如何在 CnetOS 7 或 RHEL 7(Red Hat 企业版 Linux)服务器上安装和配置 KVM(基于内核的虚拟机)?如何在 CentOS 7 上设置 KVM 并使用云镜像 / cloud- ...
- Java之——23种设计模式汇总
在软件开发的历程中,正是无数前辈们本着追求完美的架构设计和代码设计的初心.经过无数前辈们的探索和努力,逐渐形成了一系列的设计原则和设计模式. 对于Java语言来说,通常包含有6大设计原则和23种设计模 ...
- String实例 (练习)
练习题1:用户输入一段字符串,要求统计出在该段字符串中,数字,字母以及其他字符各出现过几次??? 代码实现: 运行结果: 补充:1. 连接符的使用: +用作连接符时,只能连接字符串,即“ ”双 ...
- 1994_An Algorithm To Reconstruct Wideband Speech From Narrowband Speech Based On Codebook Mapping
论文地址:基于码本映射的窄带语音宽带重建算法 博客作者:凌逆战 博客地址:https://www.cnblogs.com/LXP-Never/p/12144324.html 摘要 本文提出了一种从窄带 ...
- Ajax0001:ajax介绍 JSON数据处理
- Android Studio 快捷方式记录
- 【React Native】在网页中打开Android应用程序
React Native官方提供Linking库用于调起其他app或者本机应用.Linking的主要属性和方法有: 属性与方法 canOpenURL(url); 判断设备上是否有已经安装相应应用或可以 ...