2021-07-02

目录

文章目录

NSUOJ-Contest1199

Problem A

弟弟or哥哥?

Problem A: 弟弟or哥哥?Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 1090 Solved: 271
[Submit] [Status] [Web Board] [Creator:15310120224]

Description

闲聊群里有一个初三的小哥哥,有的人觉得别人才初三,不应该叫他小弟弟吗?哈哈哈。

如果别人问的问题比较简单,那么他应该是一个弟弟。如果问的题我们解决不了那可能就得叫他哥哥了。对吧。

今天这位小“哥哥”又来问问题了。题是这样的:

有n座山,他们连在一起成一条直线,接着从左往右给出每座山的高度a[i],现在的问题是让你求的每座山右边的第一个比它高的山是第几座山呢?如果没有则输出0

Input

测试数据有多组。对于每组测试数据:
输入一个n表示有n座山(1 <= n <= 1000000)
接着输入n个数a[i] ( 1 <= a[i] <= 1000000),表示第i座山的高度。

Output

对于每组测试数据输出每座山右边的第一个比它高的山是第几座山?如果没有则输出0

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
5
1 2 3 4 5
3
1 1 1
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
2 3 4 5 0
0 0 0

题解

使用单调栈,维护单调递减,因为后面的比前面大了,直接出栈头,并给它下标,因为第一次遇到大的。

AC代码

#include<iostream>
#include<cstring>
#include<stack>
#include<deque>
using namespace std;
stack<int> q;
int map[1000005];
//int m[1000005];
int main(){
    int t;
    while(~scanf("%d",&t)){
//        memset(m,0,sizeof(m));
        for(int i=1;i<=t;i++) {
            scanf("%d", &map[i]);
            while(!q.empty()&&map[q.top()]<map[i]){
                map[q.top()]=i;
                q.pop();
            }
            q.push(i);
        }
        while(!q.empty()){
            map[q.top()]=0;
            q.pop();
        }
        for(int i=1;i<=t;i++)    printf("%d ",map[i]);
        printf("\n");
    }
    return 0;
}

Problem B

田径场上的字符串

Problem B: 田径场上的字符串Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 829 Solved: 199
[Submit] [Status] [Web Board] [Creator:16310120805]

Description

给定一个字符串,只含有可打印字符,通过删除若干字符得到新字符串,新字符串必须满足两个条件:原字符串中出现的字符,新字符串也必须包含。 新字符串中所有的字符均不相同。新字符串的字典序是满足上面两个条件的最小的字符串。

Input

多组输入:

仅一行,有一个只含有可打印字符的字符串 s。长度小于等于1e5

Output

在一行输出字典序最小的新字符串。

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
4444555666
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
456
HINT

字符串中包含空格

题解

要求不能重复,删除其中字符得到最小字典序,可以先遍历一遍,记录他字符出现的次数,然后维护一个单调递增的栈,但是发现前面的字符已经是最后一次了就不能出它了,不然出了它就没有它了。

556465在这个样例中,输出为465,因为4遇到前面的比他大,而且前面的字符不是最后一次出现,不管后面怎么样,4在前面比5或者6在前面的字典序要小。

AC代码

#include <iostream>
#include<algorithm>
#include<stack>

#define IOS  ios::sync_with_stdio(false)
#define endl "\n"
#define input(num) scanf("%d",&num)
#define output(num, ch) printf("%d%s",num,ch)
using namespace std;
const int N = 1e6 + 10;
int a[200];
int b[200];
stack<char> q;
stack<char> k;

int main() {
    IOS;
    string str;
    while (getline(cin, str)) {
        for (char i : str) {
            a[i]++;
            b[i] = 0;
        }
        for (char i : str) {
            a[i]--;
            if (!b[i]) {
                while (!q.empty() && q.top() >= i && (a[q.top()] || q.top() == i)) {
                    b[q.top()] = 0;
                    q.pop();
                }
                q.push(i);
                b[i] = 1;
            }
        }
        while (!q.empty()) {
            k.push(q.top());
            q.pop();
        }
        while (!k.empty()) {
            cout << k.top();
            k.pop();
        }
        cout << endl;
    }
    return 0;
}

Problem C

田径场上的ZYS

Problem C: 田径场上的ZYSTime Limit: 1 Sec Memory Limit: 128 MB
Submit: 457 Solved: 172
[Submit] [Status] [Web Board] [Creator:16310120805]

Description

夏季到了,又到了露胳膊,露腿的季节。每天晚上zys都会去田径场跑步锻炼身体,为的就是“穿衣显瘦,脱衣有肉”。他说跑的太快对身体不好,所以他不想跑的太快了,但是他又不想跑的太慢了。现在田径场上有一队小姐姐排成一列,在跑步,人数为N,每人速度为V。zys就想在这列小姐姐旁边跑步,顺便liaolaio.已经知道zys最多可以交流的小姐姐数为M。为了方便交流,zys需要提前知道每个M区间小姐姐的最大速度与最小速度。

为了方便计算,一列小姐姐不会形成环

Input

*多组输入:*

第一行*输入:*N<=1e6,M<=N**

*第二行输入*N个V; 0<V<=1e5**

Output

按顺序输出N-M+1行

每行表示长度为M的区间的小姐姐的最大速度与最小速度。

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
10 3
6 4 10 10 8 6 4 2 12 14
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
4 10
4 10
8 10
6 10
4 8
2 6
2 12
2 14

题解

求各个M长度的区间的最大值最小值,维护两个单调队列,递增队列找最小,递减队列找最大。

如果要找最小,有一个数,队尾的数比这个数大,我们但是这个数的下标又在它的后面,又比它小,可以放心的移除它。

我们在找一个区间的最小的时候,如1 2 3我们知道最小的是1,但是它的下标也很小,虽然后面的比他大,但是1要是不在区间里面了,2就有可能是最小的,3也不能出,可能2不在区间里面了,可能3是最小的。

但是要是1 3 2最小的还是1,但是1要是不在区间里面了,最小的也是2,而且3还比2先出,3就是最没用的,3就可以放心的出掉。

AC代码

#include <iostream>
#include<algorithm>
#include<stack>
#include<deque>

#define IOS  ios::sync_with_stdio(false)
#define endl "\n"
#define input(num) scanf("%d",&num)
#define output(num, ch) printf("%d%s",num,ch)
using namespace std;
const int N = 1e6 + 10;
int a[N];
//int b[N];
deque<int> q;
deque<int> k;

int main() {
    IOS;
    int n, m;
    while (cin >> n >> m) {
        q.clear();
        k.clear();
        for (int i = 1; i <= n; i++)
            cin >> a[i];
        for (int i = 1; i <= n; i++) {
            if (i - m == q.front())
                q.pop_front();
            if (i - m == k.front())
                k.pop_front();
            while (!q.empty() && a[q.back()] <= a[i])
                q.pop_back();
            while (!k.empty() && a[k.back()] >= a[i])
                k.pop_back();
            q.push_back(i);
            k.push_back(i);
            if (i >= m)
                cout << a[k.front()] << " " << a[q.front()] << endl;
        }
    }
    return 0;
}

Problem D

田径场的最大矩形面积

Problem D: 田径场的最大矩形面积Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 369 Solved: 79
[Submit] [Status] [Web Board] [Creator:16310120805]

Description

总所周知,每次体体测的时候,都是很多班级在观光台前集合,由于每个班人数不一样,有排三列的有排两列的,还有排一列的,切没列人数不一样,老师站在观光台上,看着很不舒服,他想找出围成的最大矩形面积。毕竟为了评估。为了简化问题,现在固定每个同学的位置,最大方阵以外的同学需要围绕操场跑圈圈。因为后面的同学极有可能是迟到的,为了让最少的同学跑圈圈,所以想到了最大矩形面积。

为了简化问题,每个班能够构成一个矩形(即每列的人数相等)

如图所示

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nvBFZy2Z-1625225468792)(http://acm.nsu.edu.cn/JudgeOnline/upload/image/20190415/20190415214225_56148.png)]

Input

输入一个N,代表下面有N个班级。(0<n<=1000000)

输入N班级队伍的列数ai,(1=<ai<=100)

输入N班级队伍的宽度bi.(1<=bi<1000000000)

Output

输出一行表示 最大矩形面积

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
72 1 4 5 1 3 31 1 1 1 1 1 1
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
8

题解

找一个矩形面积最大的。维护单调递增的栈。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FsK6Iayr-1625225468801)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20210625171740983.png)]

2 1 4 5 1 3 3

发现2,栈里面没值,直接进。

发现1,栈里面的2被1挡住了,肯定跟后面连不起来,就不需要管2了,直接出栈,但是1比2小,可以与2连接,把1的宽度变为2.

发现4,但是1和4都不知道后面有多少比他们大的数,比他们大的都可以连接,4直接入栈。

发现5,同4,不知道后面有多少比他们大的,直接入栈。

发现1,5比它大,5跟后面连接不起来了,把5出栈,栈头4比1大,出4,不过要注意4是第二个出的,要加上5的宽度,4前面的都比4小,后面的都比4大,所以要记录4后面的宽度,栈中的1也是如此。最后1进栈,加上刚刚最后一个出栈的宽度,因为最后一个最小,肯定是连接了之前出的那些数,而且这个数也比最后一个出栈的要小或者等于,肯定能连接,直接加上,最后出栈的就是 它本来的宽度,连接比它大的宽度,因为这个数也能与最后出栈的相连接,所以就加上最后出栈的那个数的宽度。

AC代码

#include <iostream>
#include<algorithm>
#include<stack>
#include<deque>
#include<vector>

#define IOS  ios::sync_with_stdio(false)
#define endl "\n"
using namespace std;
const int N = 1e6 + 10;
long long a[N];
long long b[N];
stack<long long> q;

int main() {
//    IOS;
    long long n;
    while (~scanf("%lld", &n)) {
        for (int i = 0; i < n; i++)
            scanf("%lld", &a[i]);
        for (int i = 0; i < n; i++)
            scanf("%lld", &b[i]);
        a[n] = b[n] = 0;
        for (int i = 0; i <= n; i++) {
            long long m = 0;
            while (!q.empty() && a[q.top()] >= a[i]) {
                m = b[q.top()] += m;
                q.pop();
            }
            q.push(i);
            b[i] += m;
        }
        q.pop();
        long long m = 0;
        for (int i = 0; i < n; i++)
            m = max(m, a[i] * b[i]);
        printf("%lld\n", m);
    }
    return 0;
}

Problem E

田径场上的view

Problem E: 田径场上的viewTime Limit: 1 Sec Memory Limit: 128 MB
Submit: 66 Solved: 8
[Submit] [Status] [Web Board] [Creator:16310120805]

Description

由于pq上学期体育课,选修了田径,眼看天气越来越热了,为了减少太阳的烘烤,上田径课的时候,pq选择站在两个同学中间,现在pq抬头望天空,他想知道他能看到天空的最大角度为多少?为了表示pq的良心,假设田径场上,上课时,同学们都站在一条直线上,当然大家都知道,田径课上,大家都是拖拖拉拉,所以,刚开始上课的时候不一定每个位置都有人,但是,pq都左右两边肯定是有人的。每一个同学都有一个高度,并且pq的身高忽略不计。已知现在有N个同学,N个身高。Q次查询,代表pq在不同位置时所能看到的天空最大视野角度。

Input

第一行输入:N(1=<N<=1e5)个同学

输入N行:xi hi(xi代表同学的位置,hi代表该同学的身高 1≤xi,hi≤1e7)

下面输入Q次查询 ( 0<Q≤1e5)

输入Q行:每行一个数W 表示查询在W位置时所能看到的天空最大视野角度

Output

对于每个查询,您应该输出在W位置时所能看到的天空最大视野角度。答案保留两位小数

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
31 22 15 114
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
101.31

题解

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CGwV4Ra9-1625225468803)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20210625194720609.png)]

假如第三根柱子为人,第二根柱子比第一根高,人又在右边,肯定能挡住第一根。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4NHE033R-1625225468804)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20210625195716159.png)]

人在(p3,p4)的范围,看到的是p3,人在(p4,p5)看到的是p2,人在大于p5看到的是p1。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ut8Tj2Ay-1625225468805)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20210625200903131.png)]

栈存的柱子到了p3,所以现在只考虑大于p3位置的人,人在(p3,p5)看的到p3,人在p5之后看的到p1,因为p2对于p3来说要在p6才能看到p2,但是p1对于p2来说在大于p4就只能看见p1了,而且p1到p2的线比p2到p3的线更斜,p4肯定在p6前,p2是多余的,就应该把它出掉。所以这种角度边小了是不行的,维护一个单调递增栈。

然后根据这个反方向再跑一次就行。

AC代码

//#pragma GCC optimize(3)#include <iostream>#include<algorithm>#include<stack>#include<queue>#include<vector>#include<map>#include<cmath> #define PI acos(-1)#define IOS  ios::sync_with_stdio(false)#define endl "\n"using namespace std;const int N = 2e5 + 10;struct no {    int x;    int h;    double k;    int id;} zqq[N];stack<int> wrc; bool cmp(no aa, no bb) {    return aa.x < bb.x;} bool cid(no aa, no bb) {    return aa.id < bb.id;} void clear(stack<int> &zll) {    stack<int> wrr;    zll = wrr;} bool check(int i, int j, int p) {    return atan((double) abs(zqq[i].h - zqq[j].h) / (double) abs(zqq[j].x - zqq[i].x)) * 180 / PI <           atan((double) abs(zqq[j].h - zqq[p].h) / (double) abs(zqq[j].x - zqq[p].x)) * 180 / PI;} int main() {//    IOS;    int n, q;    scanf("%d", &n);    for (int i = 0; i < n; i++) {        scanf("%d%d", &zqq[i].x, &zqq[i].h);        zqq[i].id = 0;    }    scanf("%d", &q);    for (int i = n; i < n + q; i++) {        scanf("%d", &zqq[i].x);        zqq[i].id = i;    }    sort(zqq, zqq + n + q, cmp);    for (int i = 0; i < n + q; i++) {        while (!wrc.empty() && zqq[wrc.top()].h <= zqq[i].h)            wrc.pop();        while (!wrc.empty()) {            int k = wrc.top();            wrc.pop();            if (wrc.empty() || check(wrc.top(), k, i)) {                wrc.push(k);                break;            }        }        if (zqq[i].h == 0)            if (!wrc.empty())                zqq[i].k = atan((double) abs(zqq[i].h - zqq[wrc.top()].h) /                                (double) abs(zqq[i].x - zqq[wrc.top()].x)) * 180 / PI;        wrc.push(i);    }    clear(wrc);    for (int i = n + q - 1; i >= 0; i--) {        while (!wrc.empty() && zqq[wrc.top()].h <= zqq[i].h)            wrc.pop();        while (!wrc.empty()) {            int k = wrc.top();            wrc.pop();            if (wrc.empty() || check(wrc.top(), k, i)) {                wrc.push(k);                break;            }        }        if (zqq[i].h == 0)            if (!wrc.empty())                zqq[i].k += atan((double) abs(zqq[i].h - zqq[wrc.top()].h) /                                 (double) abs(zqq[i].x - zqq[wrc.top()].x)) * 180 / PI;        wrc.push(i);    }    sort(zqq, zqq + q + n, cid);    for (int i = n; i < n + q; i++)        printf("%.2f\n", 180 - zqq[i].k);    return 0;} /**************************************************************    Problem: 2773    User: 20320220114    Language: C++    Result: Accepted    Time:760 ms    Memory:7184 kb****************************************************************/

Problem F

AC???!!!

Problem F: AC???!!!Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 131 Solved: 10
[Submit] [Status] [Web Board] [Creator:Imported]

Description

又开一套题了,现在zser学长打算检测上一套题的做题量,zser想知道在正在检测的做题量中最高的有多少道。于是他打算编写一个程序来计算。

Input

输入数据第一行为一整数T,代表有T组输入(T<= 50)

第一行输入ZserGo,表示检测开始

接下来数据由三个情况:

C,Name,Value,zser在检测名字为Name的做题量为Value的同学(名字长度不大于5,0 <= Value <= 1000000000)

G,zser不在检测队伍最前面同学的做题量

Q,zser想知道正在检测的做题量中最高的有多少道

最后一行为 END,代表所有的检测接受

zser同时检测的同学总人数不超过1000000

Output

对于每个询问Q,输出 zesr 当前正在检测同学中最高的做题量,没有检测的同学时输出-1

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
2STARTC zser 1000000000C zml 0QGQENDSTARTQC zml 200C zser 100QGQC one 500QEND
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
10000000000-1200100500
HINT

当心,zser在没有人的时候任可能执行G操作

题解

维护单调队列,单调递减,因为后面要是大了,队列里面比他小的就没用了,比他小,又比他先出,根本没有输出机会。

卡时间很厉害,用数组模拟双端队列。

AC代码

#include <iostream>#include<algorithm>#include<stack>#include<deque>#include<vector>#include<map> #define IOS  ios::sync_with_stdio(false)#define endl "\n"using namespace std;const int N = 1e7 + 10;int a[N];//int b[N];int q[N]; int read() {    int x = 0, f = 1; //f是记录是否是负数 x是读入的数    char ch = getchar();    while (ch < '0' || ch > '9')//或者写成while(!isdigit(ch)) isdigit判断是否是数字    {        if (ch == '-') f = -1;//如果读入的数是字符,标记f        ch = getchar();    }    while (ch >= '0' && ch <= '9')//或者写成while(isdigit(ch))    {        x = x * 10 + ch - '0';//将读入的ASCII字符转换为数字        ch = getchar();//继续读入    }    return x * f;//将读取完毕的字符返回} string readStr() {    string s;    char ch = getchar();    while (isalpha(ch)) {//或者写成while(!isdigit(ch)) isdigit判断是否是数字        s += ch;        ch = getchar();    }    return s;} int main() {//    IOS;    int t = read();    while (t--) {        int i = 1, j = 1;        int p = 0, k = 0;        string str;        str = readStr();        while (str != "END") {            str = readStr();            if (str == "END")                break;            else if (str == "C") {                string name = readStr();                a[i] = read();                while (p != k && a[q[p]] <= a[i])                    p--;                q[++p] = i++;            } else if (str == "G") {                if (p != k && q[k + 1] == j++)                    k++;            } else if (str == "Q") {                if (p == k)                    printf("-1\n");                else                    printf("%d\n", a[q[k + 1]]);            }        }    }    return 0;} /**************************************************************    Problem: 2766    User: 20320220114    Language: C++    Result: Accepted    Time:522 ms    Memory:80216 kb****************************************************************/

Problem G

表达式求值(1)初级版

Problem G: 表达式求值(1)初级版Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 174 Solved: 49
[Submit] [Status] [Web Board] [Creator:Imported]

Description

ACM队想做一个计算器,但是,他们要做的不仅仅是一计算一个A+B的计算器,他们想实现随便输入一个表达式都能求出它的值的计算器,现在请你帮助他们来实现这个计算器吧。
比如输入:“1+2/4=”,程序就输出1.50(结果保留两位小数)

Input

第一行输入一个整数n,共有n组测试数据(n<100)。
每组测试数据只有一行,是一个字符串,表示这个运算式,每个运算式都是以“=”结束。这个表达式里只包含±*/与小括号这几种符号。其中小括号可以嵌套使用。输入保证合法,也不会出现负数。(很简单的表达式求值哦,测试数据很水的)

Output

每组都输出该组运算式的运算结果,输出结果保留两位小数。

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
2
1.000+2/4=
((1+2)*5+1)/4=
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
Case #1: 1.50
Case #2: 4.00

题解

这个题用栈模拟计算,维护一个单调递增的栈,前括号直接进,后括号必须遇见前括号才停止,我后面的优先级低,我影响不到前面优先级高的了,就可以先把前面优先级高的计算了,只有优先级比前面的高,现在还不知道有没有更高的,不知道算不算,就先留着,也就形成了单调递增。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#include<map>#include<sstream> #define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e5 + 10;char Op[4][2] = {{'*', '/'}, {'+', '-'}, {'(', ')'}, {'='}}; bool check(char a, char b) {    int aa, bb;    for (int i = 0; i < 4; i++) {        for (int j = 0; j < 2; j++) {            if (a == Op[i][j])                aa = i;            if (b == Op[i][j])                bb = i;        }    }    return aa > bb;} int main() {//    IOS;    int nn, pppp = 0;    cin >> nn;    while (nn--) {        stack<double> num;        stack<char> op;        string pp, s;        cin >> pp;        int r = 0;        while (pp[r] < '0' || pp[r] > '9') {            op.push('(');            r++;        }        for (int i = r; i < pp.size(); i++)            s += pp[i];        stringstream line;        line << s;        double n;        while (line >> n >> s) {            string p;            int k = 0;            line.clear();            num.push(n);            while (k < s.size() && (s[k] < '0' || s[k] > '9')) {                if (s[k] == '(')                    op.push(s[k]);                else {                    if (op.empty() || check(op.top(), s[k])) {                        op.push(s[k]);                    } else {                        while (!op.empty() && !check(op.top(), s[k]) && op.top() != '(') {                            double b = num.top();                            num.pop();                            double a = num.top();                            num.pop();                            if (op.top() == '+')                                a += b;                            else if (op.top() == '-')                                a -= b;                            else if (op.top() == '/')                                a /= b;                            else if (op.top() == '*')                                a *= b;                            op.pop();                            num.push(a);                        }                        if (!op.empty() && op.top() == '(' && s[k] == ')')                            op.pop();                        else                            op.push(s[k]);                    }                }                k++;            }            for (int i = k; i < s.size(); i++)                p += s[i];            line << p;        }        pppp++;        printf("Case #%d: %.2f\n", pppp, num.top());    }    return 0;}//2*(1+1)-(3/2+1)*(12*(5-2*(12+3)))=/**************************************************************    Problem: 2054    User: 20320220114    Language: C++    Result: Accepted    Time:1 ms    Memory:2168 kb****************************************************************/

Problem H

表达式求值(2)中级版

Problem H: 表达式求值(2)中级版Time Limit: 1 Sec Memory Limit: 512 MB
Submit: 224 Solved: 35
[Submit] [Status] [Web Board] [Creator:Imported]

Description

ACM团队对你所做的初级版的表达式求值软件并不满意,他们还想你增添判断表达式是否合法的功能以及乘方功能,所以希望你能重新做一份。必须包括整数、小数之间的+、-、*、/、^运算,同时只有小括号参与运算。

Input

有多组测试数据,对于每组测试数据输入一个表达式并以“=”结束该组输入。

Output

如果表达式还有除数为0的情况,输出Error!";

否则,输出该表达式的正确结果(保留4位小数)。

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
2.1234*2=(1.2+1)/0=
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
Case #1: 4.2468Case #2: Error!

题解

与G题类似,不过多了一个判断除0和一个^乘方,我怀疑数据里面会有负数或者能运算出负数,因为我RE了很多次,最后发现应该是符号多了,把数字出去就会变多,可能是有负数,把负号当作了运算符号

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#include<map>#include<sstream> #define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e5 + 10;char Op[5][2] = {{'^', ','}, {'*', '/'}, {'+', '-'}, {'(', ')'}, {'='}}; bool check(char a, char b) {    int aa, bb;    for (int i = 0; i < 5; i++) {        for (int j = 0; j < 2; j++) {            if (a == Op[i][j])                aa = i;            if (b == Op[i][j])                bb = i;        }    }    return aa > bb;} int main() {//    IOS;    int pppp = 0;    string pp;    while (cin >> pp) {        bool y = true;        stack<double> num;        stack<char> op;        string s;        int r = 0;        while (r < pp.size() && (pp[r] < '0' || pp[r] > '9') && pp[r] != '-') {            op.push(pp[r]);            r++;        }        for (int i = r; i < pp.size(); i++)            s += pp[i];        stringstream line;        line << s;        double n;        while (line >> n >> s) {//            cout << n << endl;//            cout << s << endl;            string p;            int k = 0;            line.clear();            num.push(n);            bool x = false;            while (k < s.size() && (s[k] < '0' || s[k] > '9')) {//                if (s[k] != ')' && x)//                    break;                if (s[k] != ')' && s[k] != '(') {                    if (x)                        break;                    else                        x = true;                }                if (s[k] == '(' || op.empty() || check(op.top(), s[k])) {                    op.push(s[k]);                } else {                    while (!op.empty() && !check(op.top(), s[k]) && op.top() != '(') {                        double b = 0, a = 0;//                            if (!num.empty()) {                        b = num.top();                        num.pop();//                            }//                            if (!num.empty()) {                        a = num.top();                        num.pop();//                            }                        if (op.top() == '+')                            a += b;                        else if (op.top() == '-')                            a -= b;                        else if (op.top() == '/') {                            if (b == 0.0) {                                y = false;                                break;                            } else                                a /= b;                        } else if (op.top() == '*')                            a *= b;                        else if (op.top() == '^')                            a = pow(a, b);                        if (!op.empty())                            op.pop();                        num.push(a);                    }                    if (!op.empty() && op.top() == '(' && s[k] == ')')                        op.pop();                    else                        op.push(s[k]);                }//                if (s[k] != ')' && s[k] != '(') {//                    if (x)//                        break;//                    else//                        x = true;//                }                if (!y)                    break;                k++;            }            if (!y)                break;            for (int i = k; i < s.size(); i++)                p += s[i];//            cout << p << endl;            line << p;        }        pppp++;        if (num.empty())            num.push(0);        if (y)            printf("Case #%d: %.4f\n", pppp, num.top());        else printf("Case #%d: Error!\n", pppp);    }    return 0;}//2*(1+1)-(3/2+1)*(12*(5-2*(12+3)))=//2*(1+1)-(3^2+1)*(12*(5-2*(12+3)))=/**************************************************************    Problem: 2057    User: 20320220114    Language: C++    Result: Accepted    Time:2 ms    Memory:2416 kb****************************************************************/

Problem I

Unique Number

Problem I: Unique NumberTime Limit: 2 Sec Memory Limit: 512 MB
Submit: 1005 Solved: 223
[Submit] [Status] [Web Board] [Creator:Imported]

Description

Junhan特别喜欢排序,据传拥有排序小王子的他发明了一个神奇的算法,它不仅可以快速的排序,还可以去掉里面重复的数字。为了证明它算法的优越性,它设下擂台,广征天下豪杰,比拼去重排序。-

Input

测试数据包含多组,请处理到EOF结束。

每组测试数据第一行包含一个整数N ( 1 < = n < = 100000 ),第二行包含N个数ai ( -10^9 < = ai < = 10^9 )

Output

对于每组测试数据要求首先输出去重后所剩下的数字个数m,接下来输出从大到小排好序的m个数,每两个数之间以空格分隔,注意最后一个数字后面没有多余的空格。

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
10 1 2 3 4 2 4 5 6 9 153 3 4 2 4
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
7 9 6 5 4 3 2 13 4 3 2

题解

使用排序和去重的函数就可以了

AC代码

#include<iostream>#include<algorithm>#include<functional>using namespace std;int a[100005];int main(){    int n,m,i;    while(~scanf("%d",&n)) {        for (i = 0; i < n; i++)            scanf("%d", &a[i]);        sort(a, a + n, greater<int>());        m = unique(a, a + n) - a;        printf("%d ", m);        for (i = 0; i < m ; i++)            printf("%d ", a[i]);    }    return 0;}/**************************************************************    Problem: 2001    User: 20320220114    Language: C++    Result: Accepted    Time:1092 ms    Memory:2484 kb****************************************************************/

Problem J

《8》

Problem J: 《8》Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 326 Solved: 51
[Submit] [Status] [Web Board] [Creator:Imported]

Description

众所周知,飛機飛过天空学长喜欢听李志的歌(听天空之城就知道为什么了),连2016年发行的公益专辑《8》也不例外(但是大多数人难以接受)。大数nsir也很喜欢这张专辑,nsir很大,他可以从0到10100之间任意改变,当他听到这张专辑的时候他在想一个问题,他想让自己每一位的数字重新排列,这个排列后的new_nsir能够被8整除,问最大的new_nsir是多少。如果不满足,new_nsir=-1。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BdealU9x-1625225468806)(data:image/jpeg;base64,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)]

Input

多组输入

每行输入一个nsir(0<=nsir<=10100)

Output

输出new_nsir

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
01480
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
0-1840
HINT

写不出来可以听听《8》

题解

8有个特性,因为1000能被8整除,那么只要后面是000,那么都是1000的倍数,也是8的倍数,所以只需要后面3个数能被8整除,那么这个数就能被8整除,要找一个字典序最大的,那么这三个数一定是组合起来能被8整除,而且字典序最小的,在这三个里面又要形成最大的。

AC代码

#include <iostream>#include<algorithm>#include<stack>#include<deque>#include<vector>#include<map> #define IOS  ios::sync_with_stdio(false)#define endl "\n"using namespace std;const int N = 2e6 + 10;int a[10];int b[4];int c[4];string p;  void dfs(int n) {    if (n > 3) {        int g;        int r = -1;//        for (int i = 1; i <= 3; i++) {//            cout << b[i];//        }//        cout << endl;        for (int i = 1; i <= 3; i++) { ;            for (int j = 1; j <= 3; j++) {                if (j != i) {                    for (int k = 1; k <= 3; k++) {                        if (k != i && k != j) {                            g = b[i] * 100 + b[j] * 10 + b[k];                            if (g % 8 == 0) {//                                cout<<"####"<<endl;//                                cout<<r<<endl;//                                cout<<g<<endl;//                                cout<<i<<" "<<j<<" "<<k<<endl;//                                cout<<b[i]<<" "<<b[j]<<" "<<b[k]<<endl;                                r = max(r, g);                            }                        }                    }                }            }        }        string x;        if (r != -1) {            for (int i = 9; i >= 0; i--) {//                cout << i << "@" << a[i] << endl;                for (int j = 1; j <= a[i]; j++) {                    x += char(i + '0');                }            }//            cout << "#" << r << endl;//            cout << x << endl;            int e = 3;            while (e) {                c[e] = r % 10;                r /= 10;                e--;            }            for (int i = 1; i <= 3; i++)                x += char(c[i] + '0');            p = max(p, x);        }        return;    }    for (int i = 0; i <= 9; i++) {        if (a[i]) {            b[n] = i;            a[i]--;            dfs(n + 1);            a[i]++;        }    }} string pro(int r, int w) {    string q;    if (w == 1 && r % 8 == 0)        return q + char(r + '0');    else if (w == 2) {        string x;        int l = r % 10 * 10 + r / 10;        if (r % 8 == 0 || l % 8 == 0) {            if (r % 8 == 0 && l % 8 == 0) {                r = max(r, l);            } else if (l % 8 == 0) {                r = l;            }            char aa = r / 10 + '0';            char bb = r % 10 + '0';            x += aa;            x += bb;//            cout << x << endl;        }        return x;    }    return q;} int main() {    string s;    while (cin >> s) {        p = "";        int r = 0;        for (int i = 0; i <= 9; i++)            a[i] = 0;        for (char i : s) {            a[i - '0']++;            r = r * 10 + i - '0';        }        if (s.size() < 3) {            p = pro(r, s.size());        } else            dfs(1);        if (p.empty())            cout << -1 << endl;        else cout << p << endl;    }    return 0;} /**************************************************************    Problem: 2697    User: 20320220114    Language: C++    Result: Accepted    Time:666 ms    Memory:2092 kb****************************************************************/

Problem K

Ananagrams

Problem K: AnanagramsTime Limit: 1 Sec Memory Limit: 128 MB
Submit: 48 Solved: 40
[Submit] [Status] [Web Board] [Creator:Imported]

Description

Most crossword puzzle fans are used to anagrams–groups of words with the same letters in different orders–for example OPTS, SPOT, STOP, POTS and POST. Some words however do not have this attribute, no matter how you rearrange their letters, you cannot form another word. Such words are called ananagrams, an example is QUIZ.
Obviously such definitions depend on the domain within which we are working; you might think that ATHENE is an ananagram, whereas any chemist would quickly produce ETHANE. One possible domain would be the entire English language, but this could lead to some problems. One could restrict the domain to, say, Music, in which case SCALE becomes a relative ananagram (LACES is not in the same domain) but NOTE is not since it can produce TONE.
Write a program that will read in the dictionary of a restricted domain and determine the relative ananagrams. Note that single letter words are, ipso facto, relative ananagrams since they cannot be ``rearranged’’ at all. The dictionary will contain no more than 1000 words.

Input

Input will consist of a series of lines. No line will be more than 80 characters long, but may contain any number of words. Words consist of up to 20 upper and/or lower case letters, and will not be broken across lines. Spaces may appear freely around words, and at least one space separates multiple words on the same line. Note that words that contain the same letters but of differing case are considered to be anagrams of each other, thus tIeD and EdiT are anagrams. The file will be terminated by a line consisting of a single #.

Output

Output will consist of a series of lines. Each line will consist of a single word that is a relative ananagram in the input dictionary. Words must be output in lexicographic (case-sensitive) order. There will always be at least one relative ananagram.

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
ladder came tape soon leader acme RIDE lone Dreis peatScAlE orb eye Rides dealer NotE derail LaCeS drIednoel dire Disk mace Rob dries#
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
DiskNotEderaildrIedeyeladdersoon

题解

题意找没有字母相同的,我们把字符全部转成小写,字符里面按字典序排序,遍历一波,没有一样的就输出原数组。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#include<map>#include<sstream> #define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)#define INF 0x3f3f3f3fusing namespace std;const int N = 1e3 + 10;string zqq[N];string wrc[N]; int main() {//    IOS;    string s;    int k = 0;    stringstream str;    while (getline(cin, s) && s != "#") {        stringstream line(s);        while (line >> s) {            zqq[++k] = s;            for (char i : s)                if (i <= 'Z')                    wrc[k] += char(i + 'a' - 'A');                else wrc[k] += i;            sort(wrc[k].begin(), wrc[k].end());        }    }    for (int i = 1; i <= k; i++) {        bool y = true;        for (int j = 1; j <= k; j++) {            if (i != j && wrc[i] == wrc[j]) {                y = false;                break;            }        }        if (y) {            str << zqq[i];            str << " ";        }    }//    cout << str.str() << endl;    k = 0;    while (str >> s) {        wrc[++k] = s;//        cout << wrc[k] << endl;    }    sort(wrc + 1, wrc + 1 + k);    for (int i = 1; i <= k; i++)        cout << wrc[i] << endl;    return 0;}/**************************************************************    Problem: 2254    User: 20320220114    Language: C++    Result: Accepted    Time:2 ms    Memory:2228 kb****************************************************************/

Problem L

找子串

Problem L: 找子串Time Limit: 3 Sec Memory Limit: 128 MB
Submit: 109 Solved: 21
[Submit] [Status] [Web Board] [Creator:Imported]

Description

给你n个字符串,然后随后m行查询,对于每个查询字符串s,输出结果
结果: s是多少个str[i]的子串,所有存在,并且输出str[i]的字典序最大的串

Input

输入n(1<=n<=10000),紧接著n行为str[i]的字符串。输入m(1<=m<=50000)
接着m行查询,输入字符串s

(规定所有的字符串长度不超过10)

Output

对应每行输入,输出一行,如果每个s2,如果不在s1中所有的子串出现则输出0,否则输出在所有串中出现子串的次数,以及出现在字典序最大的字符串是哪个

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa16aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
8 aaaaaaaa7 aaaaaaaa6 aaaaaaaa5 aaaaaaaa4 aaaaaaaa3 aaaaaaaa2 aaaaaaaa1 aaaaaaaa8 aaaaaaaa7 aaaaaaaa6 aaaaaaaa5 aaaaaaaa4 aaaaaaaa3 aaaaaaaa2 aaaaaaaa1 aaaaaaaa

题解

正常找字串的话, n<=1e4,m<=5e4,每个s都要去找str,复杂度就O(n2)的复杂度,复杂度太高了。这时我们可以先找出str所有子串,因为字符只有10,特别少,最多100次就能找出字符的所有子串,记录次数和最大的是谁,只有O(n)的复杂度,完全能跑出来。

把查询全部存起来,一起输出会更快,原理不知。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#include<map>#include<sstream>#include<unordered_map> #define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)#define INF 0x3f3f3f3fusing namespace std;const int N = 1e5 + 10;unordered_map<string, int> zqq;unordered_map<string, string> zz;string l[N]; int main() {    IOS;    int n, m;    cin >> n;    for (int i = 1; i <= n; i++) {        string qq;        cin >> qq;        unordered_map<string, int> cc;        for (int j = 1; j <= qq.size(); j++) {            for (int k = 0; k <= (int) qq.size() - j; k++) {                if (!cc[qq.substr(k, j)])                    zqq[qq.substr(k, j)]++;                zz[qq.substr(k, j)] = max(qq, zz[qq.substr(k, j)]);                cc[qq.substr(k, j)] = 1;            }        }    }    cin >> m;    for (int i = 1; i <= m; i++) {         cin >> l[i];    }    for (int i = 1; i <= m; i++) {        string s = l[i];        cout << zqq[s];        if (zqq[s])            cout << " " << zz[s];        cout << endl;    }    return 0;}/**************************************************************    Problem: 2701    User: 20320220114    Language: C++    Result: Accepted    Time:1148 ms    Memory:29736 kb****************************************************************/

Problem M

年度盘点

Problem M: 年度盘点Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 169 Solved: 67
[Submit] [Status] [Web Board] [Creator:Imported]

Description

圣诞节到了,元旦节还会远吗?年终了总是有各种各样的榜单,比如:《2018年度电影榜单》、《2018话题盘点》。機长也想做一个关于李志的音乐榜单,但是苦于没有数据。于是就求助四火学长,让他帮忙爬点数据。四火学长也没让機长失望,半个小时就把数据丢给了他。機长一拿到数据开始苦恼了,一堆数据没有任何的逻辑可言,于是就请你们来帮助他整理数据。

Input

每行输入一个数T(1<=T<=20)代表有T组数据。

紧接着每组数据第一行输入一个n(1<=n<=100)。然后n行输入杂乱的数据:“歌名 专辑名 点击次数”。规定每个字符串的长度不超过20.

Output

对于每一组测试数据,请你输出整理后的结果。歌按照专辑分类,按字母顺序排序,统一专辑按歌名排序,同样按照字母排序

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
17Sky_City In_Love_with_Nanjing 116514Has_Man_a_Future Has_Man_a_Future 65461Re_He_Road F 94516midian In_Love_with_Nanjing 65461Seek F 65441Nanjing_Summer_day F 65841Hangzhuo F 65415
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
F
->Hangzhuo->65415
->Nanjing_Summer_day->65841
->Re_He_Road->94516
->Seek->65441
Has_Man_a_Future
->Has_Man_a_Future->65461
In_Love_with_Nanjing
->Sky_City->116514
->midian->65461

题解

直接用专辑排序,一样的话按照歌名排序

AC代码

#include <iostream>
#include<algorithm>
#include <cstring>
#include<cmath>
#include<stack>
#include<set>
#include<queue>
#include<map>
#include<sstream>
 
#define IOS  ios::sync_with_stdio(false)
#define endl "\n"
#define PI acos(-1)
#define INF 0x3f3f3f3f
using namespace std;
const int N = 1e3 + 10;
struct no {
    string a;
    string b;
    string c;
} zqq[N];
 
bool cmp(no aa, no bb) {
    if (aa.b == bb.b)
        return aa.a < bb.a;
    return aa.b < bb.b;
}
 
int main() {
//    IOS;
    string s;
    getline(cin, s);
    stringstream l(s);
    int t;
    l >> t;
    while (t--) {
        getline(cin, s);
        stringstream p(s);
        int n;
        p >> n;
        for (int i = 1; i <= n; i++) {
            getline(cin, s);
            stringstream line(s);
            line >> zqq[i].a >> zqq[i].b >> zqq[i].c;
        }
        sort(zqq + 1, zqq + 1 + n, cmp);
        for (int i = 1; i <= n; i++) {
            if (zqq[i].b != zqq[i - 1].b)
                cout << zqq[i].b << endl;
            cout << "   ->" << zqq[i].a << "->" << zqq[i].c << endl;
        }
    }
    return 0;
}
/**************************************************************
    Problem: 2702
    User: 20320220114
    Language: C++
    Result: Accepted
    Time:18 ms
    Memory:2256 kb
****************************************************************/

Problem N

The Blocks Problem

Problem N: The Blocks ProblemTime Limit: 1 Sec Memory Limit: 512 MB
Submit: 22 Solved: 7
[Submit] [Status] [Web Board] [Creator:Imported]

Description

Many areas of Computer Science use simple, abstract domains for both analytical and empirical studies. For example, an early AI study of planning and robotics (STRIPS) used a block world in which a robot arm performed tasks involving the manipulation of blocks.

In this problem you will model a simple block world under certain rules and constraints. Rather than determine how to achieve a specified state, you will ``program’’ a robotic arm to respond to a limited set of commands.

The problem is to parse a series of commands that instruct a robot arm in how to manipulate blocks that lie on a flat table. Initially there are n blocks on the table (numbered from 0 to n-1) with block b**i adjacent to block b**i+1 for all 0<=i<n-1 as shown in the diagram below:

img
Figure:
Initial Blocks World

The valid commands for the robot arm that manipulates blocks are:

  • move

    a

    onto

    b

    where a and b are block numbers, puts block a onto block b after returning any blocks that are stacked on top of blocks a and b to their initial positions.

  • move

    a

    over

    b

    where a and b are block numbers, puts block a onto the top of the stack containing block b, after returning any blocks that are stacked on top of block a to their initial positions.

  • pile

    a

    onto

    b

    where a and b are block numbers, moves the pile of blocks consisting of block a, and any blocks that are stacked above block a, onto block b. All blocks on top of block b are moved to their initial positions prior to the pile taking place. The blocks stacked above block a retain their order when moved.

  • pile

    a

    over

    b

    where a and b are block numbers, puts the pile of blocks consisting of block a, and any blocks that are stacked above block a, onto the top of the stack containing block b. The blocks stacked above block a retain their original order when moved.

  • quit

    terminates manipulations in the block world.

Any command in which a = b or in which a and b are in the same stack of blocks is an illegal command. All illegal commands should be ignored and should have no affect on the configuration of blocks.

Input

The input begins with an integer n on a line by itself representing the number of blocks in the block world. You may assume that 0 < n < 25.

The number of blocks is followed by a sequence of block commands, one command per line. Your program should process all commands until the quit command is encountered.

You may assume that all commands will be of the form specified above. There will be no syntactically incorrect commands.

Output

The output should consist of the final state of the blocks world. Each original block position numbered i (0<=i<n where n is the number of blocks) should appear followed immediately by a colon. If there is at least a block on it, the colon must be followed by one space, followed by a list of blocks that appear stacked in that position with each block number separated from other block numbers by a space. Don’t put any trailing spaces on a line.

There should be one line of output for each block position (i.e., n lines of output where n is the integer on the first line of input).

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
10move 9 onto 1move 8 over 1move 7 over 1move 6 over 1pile 8 over 6pile 8 over 5move 2 over 1move 4 over 9quit
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
0: 01: 1 9 2 42:3: 34:5: 5 8 7 66:7:8:9:

题解

move和over都是要去掉上面的,判断一下是不是在同一个数组里面就可以。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#include<map>#include<sstream> #define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)#define INF 0x3f3f3f3fusing namespace std;const int N = 1e3 + 10;vector<int> num[30];  int main() {//    IOS;    queue<int> zqq;    string s, k;    int n;    cin >> n;    for (int i = 0; i < n; i++)        num[i].push_back(i);    while (cin >> s && s != "quit") {        vector<int>::iterator it, te, er, ra;        int qq, cc;        int a, b;        cin >> a >> k >> b;        for (int i = 0; i < n; i++) {            if (find(num[i].begin(), num[i].end(), a) != num[i].end()) {                it = find(num[i].begin(), num[i].end(), a);                qq = i;            }            if (find(num[i].begin(), num[i].end(), b) != num[i].end()) {                te = find(num[i].begin(), num[i].end(), b);                cc = i;            }        }        if (qq != cc) {            zqq.push(*it);            num[qq].erase(it);            while (it != num[qq].end()) {                if (s == "move")                    num[*it].push_back(*it);                else                    zqq.push(*it);                it = num[qq].erase(it);            }            if (k == "onto") {                te++;                while (te != num[cc].end()) {                    num[*te].push_back(*te);                    te = num[cc].erase(te);                }            }            while (!zqq.empty())                num[cc].push_back(zqq.front()), zqq.pop();        }    }    for (int i = 0; i < n; i++) {        cout << i << ":";        for (int &it : num[i]) {            cout << " " << it;        }        cout << endl;    }    return 0;}/**************************************************************    Problem: 1304    User: 20320220114    Language: C++    Result: Accepted    Time:1 ms    Memory:2104 kb****************************************************************/

Problem O

Unix ls

Problem O: Unix lsTime Limit: 1 Sec Memory Limit: 128 MB
Submit: 135 Solved: 51
[Submit] [Status] [Web Board] [Creator:Imported]

Description

The computer company you work for is introducing a brand new computer line and is developing a new Unix-like operating system to be introduced along with the new computer. Your assignment is to write the formatter for the ls function.
Your program will eventually read input from a pipe (although for now your program will read from the input). Input to your program will consist of a list of (F) filenames that you will sort (ascending based on the ASCII character values) and format into © columns based on the length (L) of the longest filename. Filenames will be between 1 and 60 (inclusive) characters in length and will be formatted into left-justified columns. The rightmost column will be the width of the longest filename and all other columns will be the width of the longest filename plus 2. There will be as many columns as will fit in 60 characters. Your program should use as few rows ® as possible with rows being filled to capacity from left to right.

Input

The input will contain an indefinite number of lists of filenames. Each list will begin with a line containing a single integer (1 <= N <= 100). There will then be N lines each containing one left-justified filename and the entire line’s contents (between 1 and 60 characters) are considered to be part of the filename. Allowable characters are alphanumeric (a to z, A to Z, and 0 to 9) and from the following set { ._- } (not including the curly braces). There will be no illegal characters in any of the filenames and no line will be completely empty.

Immediately following the last filename will be the N for the next set or the end of file. You should read and format all sets in the input.

Output

For each set of filenames you should print a line of exactly 60 dashes (-) followed by the formatted columns of filenames. The sorted filenames 1 to R will be listed down column 1; filenames R+1 to 2R listed down column 2; etc.

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
10tiny2short4mevery_long_file_nameshortersize-1size2size3much_longer_name12345678.123mid_size_name12WeaserAlfalfaStimeyBuckwheatPorkyJoeDarlaCottonButchFroggyMrs_CrabappleP.D.19Mr._FrenchJodyBuffySissyKeithDannyLoriChrisShirleyMarshaJanCindyCarolMikeGregPeterBobbyAliceRuben
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
------------------------------------------------------------12345678.123         size-12short4me            size2mid_size_name        size3much_longer_name     tinyshorter              very_long_file_name------------------------------------------------------------Alfalfa        Cotton         Joe            PorkyBuckwheat      Darla          Mrs_Crabapple  StimeyButch          Froggy         P.D.           Weaser------------------------------------------------------------Alice       Chris       Jan         Marsha      RubenBobby       Cindy       Jody        Mike        ShirleyBuffy       Danny       Keith       Mr._French  SissyCarol       Greg        Lori        Peter

题解

找最长的字符,看他有多少个,然后必须少于60字符,(max+2)*(n-1)+max <= 60

算出来

n<=(60-max)/(max+2)+1
n < = 60 − m a x m a x + 2 + 1 n<=\frac{60-max}{max+2}+1 n<=max+260max+1

AC代码

#include<iostream>#include<cstdio>#include<cctype>#include <cstring>#include<vector>#include <algorithm> #define endl "\n"#define IOS ios::sync_with_stdio(false)using namespace std;const int N = 3e5 + 10;string zqq[105]; int main() {    IOS;    int n;    while (cin >> n) {        int m = 0;        for (int i = 1; i <= n; i++) {            cin >> zqq[i];            if (zqq[i].size() > m)                m = (int) zqq[i].size();        }//        cout<<"?"<<endl;        for (int i = 1; i <= 60; i++)            cout << '-';        cout << endl;        sort(zqq + 1, zqq + 1 + n);        int k = (60 - m) / (m + 2) + 1;        int p = n / k;        if (n % k)            p++;        for (int i = 1; i <= p; i++) {            for (int j = 0; j < k; j++) {                if (i + j * p <= n) {                    cout << zqq[i + j * p];                    if (j != k - 1) {                        for (int h = (int) zqq[i + j * p].size(); h < m + 2; h++)                            cout << " ";                    }                } else break;            }            cout<<endl;        }     }    return 0;} /**************************************************************    Problem: 2125    User: 20320220114    Language: C++    Result: Accepted    Time:1 ms    Memory:2256 kb****************************************************************/

Problem P

Printer Queue

Problem P: Printer QueueTime Limit: 1 Sec Memory Limit: 128 MB
Submit: 90 Solved: 55
[Submit] [Status] [Web Board] [Creator:Imported]

Description

The only printer in the computer science students’ union is experiencing an extremely heavy workload. Sometimes there are a hundred jobs in the printer queue and you may have to wait for hours to get a single page of output.

Because some jobs are more important than others, the Hacker General has invented and implemented a simple priority system for the print job queue. Now, each job is assigned a priority between 1 and 9 (with 9 being the highest priority,
and 1 being the lowest), and the printer operates as follows.

  • The first job J in queue is taken from the queue.
  • If there is some job in the queue with a higher priority than job J, thenmove J to the end of the queue without printing it.
  • Otherwise, print job J (and do not put it back in the queue).

In this way, all those importantmuffin recipes that the Hacker General is printing get printed very quickly. Of course, those annoying term papers that others are printing may have to wait for quite some time to get printed, but that’s life.

Your problem with the new policy is that it has become quite tricky to determine when your print job will actually be completed. You decide to write a program to figure this out. The program will be given the current queue (as a list of priorities) as well as the position of your job in the queue, and must then calculate how long it will take until your job is printed, assuming that no additional jobs will be added to the queue. To simplifymatters, we assume that printing a job always takes exactly one minute, and that adding and removing jobs from the queue is instantaneous.

Input

One line with a positive integer: the number of test cases (at most 100). Then for each test case:

  • One line with two integers n and m, where n is the number of jobs in the queue (1 ≤ n ≤ 100) and m is the position of your job (0 ≤ m ≤ n −1). The first position in the queue is number 0, the second is number 1, and so on.
  • One linewith n integers in the range 1 to 9, giving the priorities of the jobs in the queue. The first integer gives the priority of the first job, the second integer the priority of the second job, and so on.
Output

For each test case, print one line with a single integer; the number of minutes until your job is completely printed, assuming that no additional print jobs will arrive.

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
3
1 0
5
4 2
1 2 3 4
6 0
1 1 9 1 1 1
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
1
2
5

题解

用优先队列和队列,看队列出的和优先队列出的优先级是不是一样的,不一样就出队再进队,一样就出队。

AC代码

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
void clear(queue<int>& q, priority_queue<int, vector<int>, less<int> >& e) {
    queue<int> empty;
    priority_queue<int, vector<int>, less<int> > we;
    swap(we, e);
    swap(empty, q);
}
int main() {
    priority_queue<int, vector<int>, less<int> > a;
    queue<int> b;
    int n, i, h;
    int x, y, s;
    scanf("%d", &n);
    while (n--) {
        s = 0;
        scanf("%d%d", &x, &y);
        for (i = 1; i <= x; i++) {
            scanf("%d", &h);
            a.push(h);
            b.push(h);
        }
        while (y != -1) {
            if (b.size() != 0 && a.size() != 0) {
                if (a.top() != b.front()) {
                    h = b.front();
                    b.pop();
                    b.push(h);
                    y--;
                    if (y == -1)
                        y = b.size()-1;
                }
                else {
                    b.pop();
                    a.pop();
                    y--;
                    s++;
                }
            }
            else break;
             
        }
        clear(b, a);
        printf("%d\n", s);
    }
 
    return 0;
}
/**************************************************************
    Problem: 2238
    User: 20320220114
    Language: C++
    Result: Accepted
    Time:6 ms
    Memory:2104 kb
****************************************************************/

Problem Q

去掉双斜杠注释

Problem Q: 去掉双斜杠注释Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 840 Solved: 109
[Submit] [Status] [Web Board] [Creator:Imported]

Description

将C程序代码中的双斜杠注释去掉。

Input

输入数据中含有一些符合C++语法的代码行。需要说明的是,为了方便编程,规定双斜杠注释内容不含有双引号,源程序中没空行。保证每行不超过1000个字符

Output

输出不含有双斜杠注释的C++代码,除了注释代码之外,原语句行格式不变。

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
//======================// simplest program//======================#includeusing namespace std;//----------------------int main(){cout<<”hello world!\n”;}//---------------------
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
#includeusing namespace std;int main(){cout<<”hello world!\n”;}
HINT

本题每一行数据的输出末尾不含有多余的空格字符!!!

题解

就判断一下是不是两个//挨在一起的。

AC代码

#include <stdio.h>char a[100][1005];int b[100];int main(){    int i=1,j,h,k,s;    while(gets(&a[i][0])!=NULL)    i++;    s=i-1;    for(i=1;a[i][0]!='\0';i++)    {        h=0;        k=0;        for(j=0;a[i][j]!='\0';j++)        {            if(a[i][j]=='"')                h=1;            if(a[i][j]=='/'&&a[i][j+1]=='/') {                if(k==0) {                    b[i] = 1;                    a[i][0] = '\0';                    break;                }                if(h==0) {                    if (j == 0)                        b[i] = 1;                    a[i][j] = '\0';                    break;                }            }            if(a[i][j]!=' ')                k=1;        }    }    for(i=1;i<=s;i++)       if(a[i][0]!='\0') {           printf("%s", a[i]);           if(b[i]==0&&i!=s)               printf("\n");       } return 0;} /**************************************************************    Problem: 1105    User: 20320220114    Language: C++    Result: Accepted    Time:1 ms    Memory:1148 kb****************************************************************/

Problem R

金额的中文大写

Problem R: 金额的中文大写Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 107 Solved: 43
[Submit] [Status] [Web Board] [Creator:Imported]

Description

读入一个浮点数值,将其转化为金额的中文大写形式。
例如:
123.45转化为“壹佰贰拾叁元肆角伍分”。

1)当金额为整数时,只表示整数部分,省略小数部分,并添加“整”字。
例如:123表示为“壹佰贰拾叁元整”

2)当金额中有连续的0时(含一个0),只需写一个“零”即可。
例如:10005表示为“壹万零伍元整”

3)10元缩写为“拾元整”。

Input

表示金额的浮点数若干,每行一个

Output

各金额的中文大写形式,每行一个

注:数字“壹贰叁肆伍陆柒捌玖拾佰仟万亿”
单位“元角分”

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
123.451231000510
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
壹佰贰拾叁元肆角伍分壹佰贰拾叁元整壹万零伍元整拾元整
HINT

数据范围上亿

题解

直接用字符串判断,有没有.就能判断是不是小数,注意中间的有贼多0的时候,除了后面全为0,统称为零,

AC代码

#include<iostream>#define W 10000#define Y 100000000using namespace std;void so(int x) {    switch (x) {    case 0:        printf("零");        break;    case 1:        printf("壹");        break;    case 2:        printf("贰");        break;    case 3:        printf("叁");        break;    case 4:        printf("肆");        break;    case 5:        printf("伍");        break;    case 6:        printf("陆");        break;    case 7:        printf("柒");        break;    case 8:        printf("捌");        break;    case 9:        printf("玖");        break;    }}void ws(int x) {    switch (x) {    case 1:        printf("拾");        break;    case 2:        printf("佰");        break;    case 3:        printf("仟");        break;    case 4:        printf("万");        break;    case 8:        printf("亿");        break;    case -1:        printf("角");        break;    case -2:        printf("分");        break;    case 200:        printf("元");        break;    case 100:        printf("元整");        break;    }}char s[20];char k1[20];char k2[20];int main() {    while (~scanf("%s", s + 1)) {        int i, m = 0, j = 1;        int x = 0;        for (i = 1; s[i] != 0; i++) {            if (m != 0) {                k2[j] = s[i];                j++;            }            if (s[i] == '.')                m = i;        }        if (m == 0) {            m = i;        }        for (i = m - 1,j=1; i >= 1; i--) {            k1[j] = s[i];            j++;        }        int h = 0, p;        x = m - 1;        for (i = m - 1; i >= 9; i--) {            p = 0;            for (m = i; m >= 9; m--)                if (k1[m] != '0')                    p = 1;            if (p == 0)                break;            if((h==0||k1[i]!='0')&&(x!=10||i!=10||k1[i]!='1'))            so(k1[i] - '0');            if (k1[i] == '0')                h = 1;            if (k1[i] != '0') {                h = 0;                ws(i - 9);            }        }        if(k1[9]!=0)        ws(8);        h = 0;        for (; i >= 5; i--) {            p = 0;            for (m = i; m >= 5; m--)                if (k1[m] != '0')                    p = 1;            if (p == 0)                break;            if ((h == 0 || k1[i] != '0') && (x!=6||i != 6 || k1[i] != '1'))                so(k1[i] - '0');            if (k1[i] == '0')                h = 1;            if (k1[i] != '0') {                h = 0;                ws(i - 5);            }        }        if(k1[5]!=0)        ws(4);        for (; i >= 1; i--) {            p = 0;            for (m = i; m >= 1; m--)                if (k1[m] != '0')                    p = 1;            if (p == 0)                break;            if ((h == 0 || k1[i] != '0' )&& (x!=2||i != 2 || k1[2] != '1'))                so(k1[i] - '0');            if (k1[i] == '0')                h = 1;            if (k1[i] != '0') {                h = 0;                ws(i - 1);            }        }        if (x == 1)            so(0);        if (k2[1] == 0) {            ws(100);        }        else {            ws(200);            if (k2[1] - '0' == 0)                so(0);            else {                so(k2[1] - '0');                if (k2[2] != '0')                    ws(-1);            }            if (k2[2] != '0'&&k2[2]!=0) {                so(k2[2] - '0');                ws(-2);            }        }        printf("\n");        for (i = 1; i < 20; i++) {            s[i] = k1[i] = k2[i] = 0;        }    }    return 0;}/**************************************************************    Problem: 1197    User: 20320220114    Language: C++    Result: Accepted    Time:1 ms    Memory:2088 kb****************************************************************/

Problem S

Time

Problem S: TimeTime Limit: 1 Sec Memory Limit: 128 MB
Submit: 207 Solved: 128
[Submit] [Status] [Web Board] [Creator:Imported]

Description

Digital clock use 4 digits to express time, each digit is described by 3*3 characters (including”|”,”_”and” “).now given the current time, please tell us how can it be expressed by the digital clock.

Input

There are several test cases.

Each case contains 4 integers in a line, separated by space.

Proceed to the end of file.

Output

For each test case, output the time expressed by the digital clock such as Sample Output.

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
1 2 5 62 3 4 2
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
 _  _  _ | _||_ |_ ||_  _||_|_  _     _ _| _||_| _||_  _|  ||_ 
HINT
The digits showed by the digital clock are as follows:_  _     _  _  _  _  _  _ | _| _||_||_ |_   ||_||_|| |||_  _|  | _||_|  ||_| _||_|

题解

给数字打表直接输出

AC代码

#include<iostream>#include<set>using namespace std;char m[10][4][4]= {{                           {" _ "},                           {"| |"},                           {"|_|"}},                   {                           {"   "},                           {"  |"},                           {"  |"},},                   {                           {" _ "},                           {" _|"},                           {"|_ "}},                   {                           {" _ "},                           {" _|"},                           {" _|"}},                   {                           {"   "},                           {"|_|"},                           {"  |"}},                   {                           {" _ "},                           {"|_ "},                           {" _|"}},                   {                           {" _ "},                           {"|_ "},                           {"|_|"}},                   {                           {" _ "},                           {"  |"},                           {"  |"}},                   {                           {" _ "},                           {"|_|"},                           {"|_|"}},                   {                           {" _ "},                           {"|_|"},                           {" _|"}},};int main(){    int k[5],i,j,l;    while(~scanf("%d",&k[1])) {        for (i = 2; i <= 4; i++)            scanf("%d", &k[i]);        for (j = 0; j < 3; j++) {            for (i = 1; i <= 4; i++) {                for (l =0;l<3;l++){                    printf("%c",m[k[i]][j][l]);                }            }            printf("\n");        }    }    return 0;}/**************************************************************    Problem: 1397    User: 20320220114    Language: C++    Result: Accepted    Time:3 ms    Memory:2084 kb****************************************************************/

Problem T

Babelfish

Problem T: BabelfishTime Limit: 1 Sec Memory Limit: 128 MB
Submit: 480 Solved: 125
[Submit] [Status] [Web Board] [Creator:Imported]

Description

You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.

Input

Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.

Output

Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as “eh”.

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
dog ogdaycat atcaypig igpayfroot ootfrayloops oopslayatcayittenkayoopslay
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
catehloops
HINT

Huge input and output,scanf and printf are recommended.

题解

用map直接一一对应,找不到就直接输出eh

AC代码

#include<iostream>#include<algorithm>#include<map>#include<string> using namespace std;int main() {    //    std::ios::sync_with_stdio(0);    //    std::cin.tie(0);    map<string, string> ma;    string a;    char e[15];    char t[15];    char d;    string b;    while (~scanf("%c", &d) && d != '\n') {        scanf("%s", e);        a = d;        a += e;        scanf("%s", t);        b = t;        getchar();        ma.insert(pair<string, string>(b, a));    }    while (~scanf("%s", t)) {        if (ma.count(t) == 1) printf("%s\n", ma[t].c_str());        else            printf("eh\n");    }    return 0;}/**************************************************************    Problem: 1891    User: 20320220114    Language: C++    Result: Accepted    Time:430 ms    Memory:13060 kb****************************************************************/

Problem U

歌词显示

Problem U: 歌词显示Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 166 Solved: 24
[Submit] [Status] [Web Board] [Creator:*13311020310]

Description

stone非常喜欢听歌,尤其雅尼的夜莺是他的最爱,每次听着夜莺的旋律 和 别人注释的意境(写在歌词文件里)总会感觉很舒服,stone非常好奇歌词是怎么写的,所以打开了歌词文件lrc,因为夜莺的歌词文件不是很适合阅读,所以在此就以gala 的 Young For You 来做 范例吧

[00:05.99]young for you
[00:15.99]Gala
[00:25.99]by: Cwind
[00:32.99]
[00:35.99]sunday’s coming i wanna drive my car
[00:39.70]to your apartment with present like a star
[00:43.69]forecaster said the weather may be rainy hard
……

看了歌词文件里面的内容,stone 有了一个想法就是写一个歌词显示器来模拟一下,不过因为一些众所周知的原因,stone 觉得还是让你们写会比较不错。

Input

首先输入歌词文件,当输入 [end]的时候表示歌词输入结束了,接下来会有一个数字n(n<=10)表示接下来有n次询问,每次询问会输入一个时间 让 歌词显示器来显示这个时间点这首歌需要显示什么歌词

有多份歌词,数据处理至文件结尾

Output

每次询问会输入一个时间 让 歌词显示器来显示这个时间点这首歌需要显示什么歌词

Sample Input [Copy](javascript:CopyToClipboard($(’#sampleinput’).text()))
[00:05.99]young for you[00:15.99]Gala[00:25.99]by:  Cwind[00:32.99][00:35.99]sunday's coming i wanna drive my car[00:39.70]to your apartment with present like a star[00:43.69]forecaster said the weather may be rainy hard[end]500:06.0000:01.0000:15.9900:33.0000:36.00
Sample Output [Copy](javascript:CopyToClipboard($(’#sampleoutput’).text()))
young for youGalasunday's coming i wanna drive my car

题解

用字符串比大小,给查询的加上[],或者只比中间的,发现比他大的就回退到上一个,输出歌词。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#include<map> #define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e5 + 10; string zqq[N]; bool check(string l, int t) {    string p;    for (int i = 1; i < 9; i++)        p += zqq[t][i];    return l >= p;} void print(int t) {    for (int i = 10; i < zqq[t].size(); i++)        cout << zqq[t][i];    cout << endl;} int main() {//    IOS;    string str;    while (getline(cin, str)) {        int k = 0;        while (str != "[end]") {            zqq[++k] = str;            getline(cin, str);        }        int n = 0;        string s;        getline(cin, s);        for (char i: s)            n = n * 10 + i - '0';        while (n--) {            string p, l;            getline(cin, p);            l += p;            int t = 1;//            cout << l << endl;            while (t <= k && check(l, t))                t++;//            cout << t << endl;            print(--t);//            cout << zqq[--t] << endl;        }    }    return 0;}/**************************************************************    Problem: 2292    User: 20320220114    Language: C++    Result: Accepted    Time:10 ms    Memory:5220 kb****************************************************************/

VJ-2021 Chengdu Neusoft Summer No.4-贪心 [回炉重造]

A

A

Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha’s friends. The i-th cup can hold at most a**i milliliters of water.

It turned out that among Pasha’s friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows:

  • Pasha can boil the teapot exactly once by pouring there at most w milliliters of water;
  • Pasha pours the same amount of water to each girl;
  • Pasha pours the same amount of water to each boy;
  • if each girl gets x milliliters of water, then each boy gets 2x milliliters of water.

In the other words, each boy should get two times more water than each girl does.

Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha’s friends.

Input

The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha’s friends that are boys (equal to the number of Pasha’s friends that are girls) and the capacity of Pasha’s teapot in milliliters.

The second line of the input contains the sequence of integers a**i (1 ≤ a**i ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha’s tea cups in milliliters.

Output

Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn’t exceed 10 - 6.

Examples

Input

2 41 1 1 1

Output

3

Input

3 184 4 4 2 2 2

Output

18

Input

1 52 3

Output

4.5

Note

Pasha also has candies that he is going to give to girls but that is another task…

题解

水杯排序,在n+11分别代表男生和女生能装最少的杯子,看n+1这个位置除以2是不是大于了1这个位置,是的话,就说明以男生为标准,女生最低的装不下,然后就用女生的最低标准来,如果大于水壶量,直接输出,因为这个最低标准已经是满足所有水杯了,但是这个都大于了水壶量,肯定有方法能合理分配完着个水壶的水,直接输出水壶水量。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;double a[N];bool cmd(double aa, double bb) {    return aa < bb;}int main() {    int n, w;    double q = 0;    scanf("%d%d", &n, &w);    for (int i = 1; i <= 2 * n; i++)        scanf("%lf", &a[i]);    sort(a + 1, a + 1 + 2 * n, cmd);    if (a[n + 1] / 2 <= a[1]) {        q = a[n + 1] * n * 3 / 2;    } else {        q = a[1] * n * 3;    }    if (q > w)        q = w;    printf("%.6f\n", q);    return 0;}

B

B

Here is a famous story in Chinese history.

That was about 2300 years ago. General Tian Ji was a high official in the country Qi. He likes to play horse racing with the king and others.

Both of Tian and the king have three horses in different classes, namely, regular, plus, and super. The rule is to have three rounds in a match; each of the horses must be used in one round. The winner of a single round takes two hundred silver dollars from the loser.

Being the most powerful man in the country, the king has so nice horses that in each class his horse is better than Tian’s. As a result, each time the king takes six hundred silver dollars from Tian.

Tian Ji was not happy about that, until he met Sun Bin, one of the most famous generals in Chinese history. Using a little trick due to Sun, Tian Ji brought home two hundred silver dollars and such a grace in the next match.

It was a rather simple trick. Using his regular class horse race against the super class from the king, they will certainly lose that round. But then his plus beat the king’s regular, and his super beat the king’s plus. What a simple trick. And how do you think of Tian Ji, the high ranked official in China?
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PQ983JM6-1625225468808)(https://vj.z180.cn/26b84969223d2bd3b9fc513cea50bb35?v=1624182157)]

Were Tian Ji lives in nowadays, he will certainly laugh at himself. Even more, were he sitting in the ACM contest right now, he may discover that the horse racing problem can be simply viewed as finding the maximum matching in a bipartite graph. Draw Tian’s horses on one side, and the king’s horses on the other. Whenever one of Tian’s horses can beat one from the king, we draw an edge between them, meaning we wish to establish this pair. Then, the problem of winning as many rounds as possible is just to find the maximum matching in this graph. If there are ties, the problem becomes more complicated, he needs to assign weights 0, 1, or -1 to all the possible edges, and find a maximum weighted perfect matching…

However, the horse racing problem is a very special case of bipartite matching. The graph is decided by the speed of the horses – a vertex of higher speed always beat a vertex of lower speed. In this case, the weighted bipartite matching algorithm is a too advanced tool to deal with the problem.

In this problem, you are asked to write a program to solve this special case of matching problem.

Input

The input consists of up to 50 test cases. Each case starts with a positive integer n ( n<=1000) on the first line, which is the number of horses on each side. The next n integers on the second line are the speeds of Tian’s horses. Then the next n integers on the third line are the speeds of the king’s horses. The input ends with a line that has a single `0’ after the last test case.

Output

For each input case, output a line containing a single number, which is the maximum money Tian Ji will get, in silver dollars.

Sample Input

392 83 7195 87 74220 2020 20220 1922 180

Sample Output

20000

题解

将两个人的马从大到小排序。

比最快的马。

田的马比的过王的马,直接比,田赢一局。

田的马比不过王的马,拿最慢的马来比王最快的马,输一局,但是王最快的马没了,只要王的马里面有比田的马慢的,就赢回来了。

田的马跟王的马一样,看两个人最慢的马谁赢,要是田的马赢,直接比最慢的马,这样赢一局。要是田的马输或者平等,让田的最慢的马来比王最快的马,这样又用最小的消耗了最大的马,后面田最快的马比王的马快,就会赢回来。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;double a[N];bool cmd(double aa, double bb) {    return aa < bb;}int main() {    int n, w;    double q = 0;    scanf("%d%d", &n, &w);    for (int i = 1; i <= 2 * n; i++)        scanf("%lf", &a[i]);    sort(a + 1, a + 1 + 2 * n, cmd);    if (a[n + 1] / 2 <= a[1]) {        q = a[n + 1] * n * 3 / 2;    } else {        q = a[1] * n * 3;    }    if (q > w)        q = w;    printf("%.6f\n", q);    return 0;}

C

C

Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there.

At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma.

They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree.

After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree.

Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations.

It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree.

Input

The first line of the input contains a single integer n (3 ≤ n ≤ 3·106) — the number of schoolchildren who will participate in the Olympiad.

The next line of the input contains two integers min1 and max1 (1 ≤ min1 ≤ max1 ≤ 106) — the minimum and maximum limits on the number of diplomas of the first degree that can be distributed.

The third line of the input contains two integers min2 and max2 (1 ≤ min2 ≤ max2 ≤ 106) — the minimum and maximum limits on the number of diplomas of the second degree that can be distributed.

The next line of the input contains two integers min3 and max3 (1 ≤ min3 ≤ max3 ≤ 106) — the minimum and maximum limits on the number of diplomas of the third degree that can be distributed.

It is guaranteed that min1 + min2 + min3 ≤ n ≤ max1 + max2 + max3.

Output

In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas.

The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree.

Examples

Input

61 52 63 7

Output

1 2 3 

Input

101 21 31 5

Output

2 3 5 

Input

61 32 22 2

Output

2 2 2 

题解

将第一,二,三学位简称为p1,p2,p3,要求p1最大,在p1最大的情况下p2最大,我们先选择p1最大,选择p2,p3最小,加起来要是比要求的多了,说明p2,p3只能选最小了,p1就是他们还差的。要是加起来少了,就把p2再拉到最大,同理,加起来比较,少了就可以直接计算p2,多了就再看p3就行了。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;int a[3][2];int b[3];int main() {    int n;    cin >> n;    for (int i = 0; i < 3; i++)        cin >> a[i][0] >> a[i][1];    if (n - a[1][0] - a[2][0] > a[0][1]) {        b[0] = a[0][1];        if (n - a[0][1] - a[2][0] > a[1][1]) {            b[1] = a[1][1];            b[2] = n - b[0] - b[1];        } else {            b[1] = n - b[0] - a[2][0];            b[2] = a[2][0];        }    } else {        b[1] = a[1][0];        b[2] = a[2][0];        b[0] = n - b[1] - b[2];    }    for (int i : b)        cout << i << " ";    cout << endl;    return 0;}

D

D

WLD likes playing with numbers. One day he is playing with NN integers. He wants to delete KK integers from them. He likes diversity, so he wants to keep the kinds of different integers as many as possible after the deletion. But he is busy pushing, can you help him?

Input

There are Multiple Cases. (At MOST 100100)

For each case:

The first line contains one integer N(0<N≤100)N(0<N≤100).

The second line contains NN integers a1,a2,…,aN(1≤ai≤N)a1,a2,…,aN(1≤ai≤N), denoting the integers WLD plays with.

The third line contains one integer K(0≤K<N)K(0≤K<N).

Output

For each case:

Print one integer. It denotes the maximum of different numbers remain after the deletion.

Sample Input

41 3 1 2 1

Sample Output

3

Hint

if WLD deletes a 3, the numbers remain is [1,1,2],he'll get 2 different numbers.if WLD deletes a 2, the numbers remain is [1,1,3],he'll get 2 different numbers.if WLD deletes a 1, the numbers remain is [1,2,3],he'll get 3 different numbers.

题解

记录总的重复出现的次数,要是要删除他的数小于这个,直接输出不同的个数,要是删除的数量大于这个,从不同的个数里面再减少。

AC代码

#include<iostream>#include<algorithm>#include<set>using namespace std;set<int> zqq;int main() {    int n, t,k;        int m;    while(~scanf("%d", &n)) {        zqq.clear();        k=0;        for (int i = 1; i <= n; i++) {            scanf("%d", &m);            if (zqq.count(m))                k++;            else zqq.insert(m);        }        scanf("%d", &t);        if (t >= k)            cout << zqq.size() - t + k << endl;        else cout << zqq.size() << endl;    }    return 0;}

E

E

Assume the coasting is an infinite straight line. Land is in one side of coasting, sea in the other. Each small island is a point locating in the sea side. And any radar installation, locating on the coasting, can only cover d distance, so an island in the sea can be covered by a radius installation, if the distance between them is at most d.

We use Cartesian coordinate system, defining the coasting is the x-axis. The sea side is above x-axis, and the land side below. Given the position of each island in the sea, and given the distance of the coverage of the radar installation, your task is to write a program to find the minimal number of radar installations to cover all the islands. Note that the position of an island is represented by its x-y coordinates.
img
Figure A Sample Input of Radar Installations

Input

The input consists of several test cases. The first line of each case contains two integers n (1<=n<=1000) and d, where n is the number of islands in the sea and d is the distance of coverage of the radar installation. This is followed by n lines each containing two integers representing the coordinate of the position of each island. Then a blank line follows to separate the cases.

The input is terminated by a line containing pair of zeros

Output

For each test case output one line consisting of the test case number followed by the minimal number of radar installations needed. “-1” installation means no solution for that case.

Sample Input

3 21 2-3 12 11 20 20 0

Sample Output

Case 1: 2Case 2: 1

题解

以点画圆,与横坐标相交,获得的区间画的圆都能包含这个点,以后端点来排序,因为要知道先结束的是谁,才能尽量多的包含点,以尾部点设圆,以前端点来看是否在区间内。

因为几个区间与第一个尾部相交,肯定以第一个的尾部为准画圆,这样可以包括几个区间,以后面的为基准的话,第一个就包括不了了。这也是为什么要以后端点来排序。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#include<map>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e5 + 10;struct no {    double x;    double y;} node[N];bool cmp(no a, no b) {    if (a.y == b.y)        return a.x < b.x;    return a.y < b.y;}int main() {    IOS;    int p = 1;    int n, m;    while (cin >> n >> m && n && m) {        bool f = true;        double x, y;        for (int i = 1; i <= n; i++) {            cin >> x >> y;            if (y > m)                f = false;            node[i].x = x - sqrt(m * m - y * y);            node[i].y = x + sqrt(m * m - y * y);        }        sort(node + 1, node + 1 + n, cmp);        int ans = 1;        if (f) {            double k = node[1].y;            for (int i = 2; i <= n; i++) {                if (node[i].x > k) {                    k = node[i].y;                    ans++;                }            }        } else            ans = -1;        cout << "Case " << p << ": " << ans << endl;        p++;    }    return 0;//}

F

F

The cows have purchased a yogurt factory that makes world-famous Yucky Yogurt. Over the next N (1 <= N <= 10,000) weeks, the price of milk and labor will fluctuate weekly such that it will cost the company C_i (1 <= C_i <= 5,000) cents to produce one unit of yogurt in week i. Yucky’s factory, being well-designed, can produce arbitrarily many units of yogurt each week.

Yucky Yogurt owns a warehouse that can store unused yogurt at a constant fee of S (1 <= S <= 100) cents per unit of yogurt per week. Fortuitously, yogurt does not spoil. Yucky Yogurt’s warehouse is enormous, so it can hold arbitrarily many units of yogurt.

Yucky wants to find a way to make weekly deliveries of Y_i (0 <= Y_i <= 10,000) units of yogurt to its clientele (Y_i is the delivery quantity in week i). Help Yucky minimize its costs over the entire N-week period. Yogurt produced in week i, as well as any yogurt already in storage, can be used to meet Yucky’s demand for that week.

Input

* Line 1: Two space-separated integers, N and S.

* Lines 2…N+1: Line i+1 contains two space-separated integers: C_i and Y_i.

Output

* Line 1: Line 1 contains a single integer: the minimum total cost to satisfy the yogurt schedule. Note that the total might be too large for a 32-bit integer.

Sample Input

4 588 20089 40097 30091 500

Sample Output

126900

Hint

OUTPUT DETAILS:
In week 1, produce 200 units of yogurt and deliver all of it. In week 2, produce 700 units: deliver 400 units while storing 300 units. In week 3, deliver the 300 units that were stored. In week 4, produce and deliver 500 units.

题解

因为存酸奶要多花钱,我可以把存的酸奶和当时的酸奶比一下,因为后面存,这两个都要花同样的钱,所以这里只需要找一个最小的就可以了。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;long long a[N];int main() {    long long n, m, s = 0, q;    long long k = 0;    scanf("%lld%lld", &n, &m);    for (int i = 1; i <= n; i++) {        long long y, p = 0;        scanf("%lld%lld", &a[i], &y);        p = a[i];        if (i == 1)            q = p;        else {            q += m;            q = p = min(q, p);        }        s += p * y;    }    printf("%lld\n", s);    return 0;}

G

G

A factory produces products packed in square packets of the same height h and of the sizes 11, 22, 33, 44, 55, 66. These products are always delivered to customers in the square parcels of the same height h as the products have and of the size 6*6. Because of the expenses it is the interest of the factory as well as of the customer to minimize the number of parcels necessary to deliver the ordered products from the factory to the customer. A good program solving the problem of finding the minimal number of parcels necessary to deliver the given products according to an order would save a lot of money. You are asked to make such a program.

Input

The input file consists of several lines specifying orders. Each line specifies one order. Orders are described by six integers separated by one space representing successively the number of packets of individual size from the smallest size 11 to the biggest size 66. The end of the input file is indicated by the line containing six zeros.

Output

The output file contains one line for each line in the input file. This line contains the minimal number of parcels into which the order from the corresponding line of the input file can be packed. There is no line in the output file corresponding to the last ``null’’ line of the input file.

Sample Input

0 0 4 0 0 1 7 5 1 0 0 0 0 0 0 0 0 0 

Sample Output

2 1 

题解

暴力模拟,把一个6*6放了,一个5*5放一个,一个4*4放一个,4个3*3放一个,然后用2*2去把空隙填了,最后剩的话,再用2*2去装,最后把算出来的箱子数全化为1*1与这些66,55,44,33,22的和相减,就能看的出来11够不够了

AC代码

#include <iostream>#include<algorithm>#include<cmath>#include<stack>#include<set>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;long long gcd(long long a, long long b) {    return b ? gcd(b, a % b) : a;}int a[7];int main() {//    IOS;    while (~scanf("%d%d%d%d%d%d", &a[1], &a[2], &a[3], &a[4], &a[5], &a[6]) &&           a[1] + a[2] + a[3] + a[4] + a[5] + a[6]) {        int n = a[6] + a[5] + a[4] + (a[3] + 3) / 4;        int k = a[4] * 5;        if (a[3] % 4 == 1)            k += 5;        else if (a[3] % 4 == 2)            k += 3;        else if (a[3] % 4 == 3)            k += 1;        if (a[2] > k)            n += (a[2] - k + 8) / 9;        k = n * 36 - a[6] * 36 - a[5] * 25 - a[4] * 16 - a[3] * 9 - a[2] * 4;        if (a[1] > k)            n += (a[1] - k + 35) / 36;        printf("%d\n", n);    }    return 0;}

H

H

As a reward for record milk production, Farmer John has decided to start paying Bessie the cow a small weekly allowance. FJ has a set of coins in N (1 <= N <= 20) different denominations, where each denomination of coin evenly divides the next-larger denomination (e.g., 1 cent coins, 5 cent coins, 10 cent coins, and 50 cent coins).Using the given set of coins, he would like to pay Bessie at least some given amount of money C (1 <= C <= 100,000,000) every week.Please help him ompute the maximum number of weeks he can pay Bessie.

Input

* Line 1: Two space-separated integers: N and C

* Lines 2…N+1: Each line corresponds to a denomination of coin and contains two integers: the value V (1 <= V <= 100,000,000) of the denomination, and the number of coins B (1 <= B <= 1,000,000) of this denomation in Farmer John’s possession.

Output

* Line 1: A single integer that is the number of weeks Farmer John can pay Bessie at least C allowance

Sample Input

3 610 11 1005 120

Sample Output

111

Hint

INPUT DETAILS:
FJ would like to pay Bessie 6 cents per week. He has 100 1-cent coins,120 5-cent coins, and 1 10-cent coin.

OUTPUT DETAILS:
FJ can overpay Bessie with the one 10-cent coin for 1 week, then pay Bessie two 5-cent coins for 10 weeks and then pay Bessie one 1-cent coin and one 5-cent coin for 100 weeks.

题解

用最大的去试,超过了,再拿更小一点的去试,一直试到最后,拿最小的超过就行了,因为这样超过最小的话,就浪费的最小。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#include<stack>#include<set>#include <cstring>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e3 + 10;long long gcd(long long a, long long b) {    return b ? gcd(b, a % b) : a;}struct no {    long long a;    long long b;} node[30];int nono[30];bool cmp(no aa, no bb) {    return aa.a > bb.a;}int n;bool check(int p) {    if (p >= n)        return node[p].b;    return node[p].b || check(p + 1);}int main() {//    IOS;    long long m;    long long ans = 0;    cin >> n >> m;    for (int i = 1; i <= n; i++)        cin >> node[i].a >> node[i].b;    int p = n + 1;    sort(node + 1, node + 1 + n, cmp);    for (int i = 1; i <= n; i++) {        if (node[i].a >= m)            ans += node[i].b;        else {            p = i;            break;        }    }    while (check(p)) {//        cout << 2 << endl;        long long s = 0;        memset(nono, 0, sizeof nono);        for (int i = p; i <= n; i++) {            while (s <= m && nono[i] <= node[i].b) {//                cout<<"##########"<<endl;//                cout<<node[i].a<<" "<<node[i].b<<endl;//                cout<<i<<"# "<<s<<endl;                s += node[i].a;                nono[i]++;            }            nono[i]--;            s -= node[i].a;        }        for (int i = n; i >= p; i--) {            while (s < m && nono[i] < node[i].b) {                s += node[i].a;                nono[i]++;            }            if (s >= m)                break;        }//        cout << s << endl;        if (s < m)            break;        long long t = -1;        for (int i = p; i <= n; i++) {            if (nono[i])                t = (t == -1 ? node[i].b / nono[i] : min(node[i].b / nono[i], t));        }        if (t <= 0)            break;        for (int i = p; i <= n; i++) {            if (nono[i])                node[i].b -= t * nono[i];        }        ans += t;    }    cout << ans << endl;    return 0;}

I

I

Our chemical biologists have invented a new very useful form of life called stripies (in fact, they were first called in Russian - polosatiki, but the scientists had to invent an English name to apply for an international patent). The stripies are transparent amorphous amebiform creatures that live in flat colonies in a jelly-like nutrient medium. Most of the time the stripies are moving. When two of them collide a new stripie appears instead of them. Long observations made by our scientists enabled them to establish that the weight of the new stripie isn’t equal to the sum of weights of two disappeared stripies that collided; nevertheless, they soon learned that when two stripies of weights m1 and m2 collide the weight of resulting stripie equals to 2sqrt(m1m2). Our chemical biologists are very anxious to know to what limits can decrease the total weight of a given colony of stripies.
You are to write a program that will help them to answer this question. You may assume that 3 or more stipies never collide together.

Input

The first line of the input contains one integer N (1 <= N <= 100) - the number of stripies in a colony. Each of next N lines contains one integer ranging from 1 to 10000 - the weight of the corresponding stripie.

Output

The output must contain one line with the minimal possible total weight of colony with the accuracy of three decimal digits after the point.

Sample Input

3723050

Sample Output

120.000

题解

因为他是变成2*sqrt(m1*m2),然后下一个就是2*sqrt(2*sqrt(m1*m2)*m3),应该去把最大的消耗了,不然m3如果是最大的,那么就太大了,m1或者m2是最大的,开方之后就少了很多,又乘一个不是最大的数,答案就小很多了。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;double a[150];bool cmp(double aa, double bb) {    return aa > bb;}int main() {    int n;    scanf("%d", &n);    for (int i = 1; i <= n; i++)        scanf("%lf", &a[i]);    sort(a + 1, a + 1 + n, cmp);    double p = a[1];    for (int i = 2; i <= n; i++)        p = 2 * sqrt(p * a[i]);    printf("%.3f\n", p);    return 0;}

J

J

Farmer John went to cut some wood and left N (2 ≤ N ≤ 100,000) cows eating the grass, as usual. When he returned, he found to his horror that the cluster of cows was in his garden eating his beautiful flowers. Wanting to minimize the subsequent damage, FJ decided to take immediate action and transport each cow back to its own barn.

Each cow i is at a location that is Ti minutes (1 ≤ Ti ≤ 2,000,000) away from its own barn. Furthermore, while waiting for transport, she destroys Di (1 ≤ Di ≤ 100) flowers per minute. No matter how hard he tries, FJ can only transport one cow at a time back to her barn. Moving cow i to its barn requires 2 × Ti minutes (Ti to get there and Ti to return). FJ starts at the flower patch, transports the cow to its barn, and then walks back to the flowers, taking no extra time to get to the next cow that needs transport.

Write a program to determine the order in which FJ should pick up the cows so that the total number of flowers destroyed is minimized.

Input

Line 1: A single integer N
Lines 2…N+1: Each line contains two space-separated integers, Ti and Di, that describe a single cow’s characteristics

Output

Line 1: A single integer that is the minimum number of destroyed flowers

Sample Input

63 12 52 33 24 11 6

Sample Output

86

Hint

FJ returns the cows in the following order: 6, 2, 3, 4, 1, 5. While he is transporting cow 6 to the barn, the others destroy 24 flowers; next he will take cow 2, losing 28 more of his beautiful flora. For the cows 3, 4, 1 he loses 16, 12, and 6 flowers respectively. When he picks cow 5 there are no more cows damaging the flowers, so the loss for that cow is zero. The total flowers lost this way is 24 + 28 + 16 + 12 + 6 = 86.

题解

要尽量先云,运输时间短和吃草多的,给他换算成比例,按比例来排序,直接进行运算,就能算出来最终的答案了。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#include<stack>#include<set>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;struct no {    int a;    int b;    double c;} node[N];//int a[N];//int b[N];//double c[N];bool cmp(no aa, no bb) {    return aa.c > bb.c;}int main() {    IOS;    int n;    long long s = 0;    cin >> n;    for (int i = 1; i <= n; i++) {        cin >> node[i].a >> node[i].b;        s += node[i].b;        node[i].c = 1.0 * node[i].b / node[i].a;    }    sort(node + 1, node + 1 + n, cmp);    long long ans = 0;    for (int i = 1; i <= n; i++) {//        cout<<node[i].a<<" "<<node[i].b<<endl;        s -= node[i].b;        ans += node[i].a * 2 * s;    }    cout<<ans<<endl;    return 0;}

K

K

Accounting for Computer Machinists (ACM) has sufferred from the Y2K bug and lost some vital data for preparing annual report for MS Inc.
All what they remember is that MS Inc. posted a surplus or a deficit each month of 1999 and each month when MS Inc. posted surplus, the amount of surplus was s and each month when MS Inc. posted deficit, the deficit was d. They do not remember which or how many months posted surplus or deficit. MS Inc., unlike other companies, posts their earnings for each consecutive 5 months during a year. ACM knows that each of these 8 postings reported a deficit but they do not know how much. The chief accountant is almost sure that MS Inc. was about to post surplus for the entire year of 1999. Almost but not quite.

Write a program, which decides whether MS Inc. suffered a deficit during 1999, or if a surplus for 1999 was possible, what is the maximum amount of surplus that they can post.

Input

Input is a sequence of lines, each containing two positive integers s and d.

Output

For each line of input, output one line containing either a single integer giving the amount of surplus for the entire year, or output Deficit if it is impossible.

Sample Input

59 237375 743200000 8496942500000 8000000

Sample Output

11628300612Deficit

题解

这个题目说的很奇怪,反正就是说连续的五个月必须亏损,因为连续的五个月亏损会重复算,可能12个月还是有盈利的。算出来最大的就可以了,要是都不行,就输出那个不行的。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;double a[150];bool cmp(double aa, double bb) {    return aa > bb;}int main() {    int n, m;    int rr;    while (~scanf("%d%d", &n, &m)) {        if (4 * n < m) rr = 10 * n - 2 * m;        else if (3 * n < 2 * m) rr = 8 * n - 4 * m;        else if (2 * n < 3 * m) rr = 6 * n - 6 * m;        else if (n < 4 * m) rr = 3 * n - 9 * m;        else rr = -1;        if (rr >= 0) printf("%d\n", rr);        else            printf("Deficit\n");    }    return 0;}

L

L

Saruman the White must lead his army along a straight path from Isengard to Helm’s Deep. To keep track of his forces, Saruman distributes seeing stones, known as palantirs, among the troops. Each palantir has a maximum effective range of R units, and must be carried by some troop in the army (i.e., palantirs are not allowed to “free float” in mid-air). Help Saruman take control of Middle Earth by determining the minimum number of palantirs needed for Saruman to ensure that each of his minions is within R units of some palantir.

Input

The input test file will contain multiple cases. Each test case begins with a single line containing an integer R, the maximum effective range of all palantirs (where 0 ≤ R ≤ 1000), and an integer n, the number of troops in Saruman’s army (where 1 ≤ n ≤ 1000). The next line contains n integers, indicating the positions x1, …, xn of each troop (where 0 ≤ xi ≤ 1000). The end-of-file is marked by a test case with R = n = −1.

Output

For each test case, print a single integer indicating the minimum number of palantirs needed.

Sample Input

0 310 20 2010 770 30 1 7 15 20 50-1 -1

Sample Output

24

Hint

In the first test case, Saruman may place a palantir at positions 10 and 20. Here, note that a single palantir with range 0 can cover both of the troops at position 20.In the second test case, Saruman can place palantirs at position 7 (covering troops at 1, 7, and 15), position 20 (covering positions 20 and 30), position 50, and position 70. Here, note that palantirs must be distributed among troops and are not allowed to “free float.” Thus, Saruman cannot place a palantir at position 60 to cover the troops at positions 50 and 70.

题解

从第一个看距离最远能放在哪个人上面,能放的话,从这个地方找到第一个不行的人,再当作第一个人,继续这个重复的,这样包括的人是最多的。

AC代码

#include <iostream>
#include<algorithm>
#include<cmath>
#include<stack>
#include<set>

#define IOS  ios::sync_with_stdio(false)
#define endl "\n"
#define PI acos(-1)
using namespace std;
const int N = 1e3 + 10;

long long gcd(long long a, long long b) {
    return b ? gcd(b, a % b) : a;
}

int a[N];
int b[N];

int main() {
    IOS;
    int n, m;
    while (cin >> n >> m && (n != -1 || m != -1)) {
        int ans = 0;
        for (int i = 1; i <= m; i++)
            cin >> a[i];
        sort(a + 1, a + m + 1);
        for (int i = 1; i <= m;) {
            int p = a[i] + n;
            int j = i;
            for (; j <= m && a[j] <= p; j++);
            ans++;
            p = a[j - 1] + n;
            int k = j;
            for (; k <= m && a[k] <= p; k++);
            i = k;
        }
        cout << ans << endl;
    }
    return 0;
}

M

M

Oh those picky N (1 <= N <= 50,000) cows! They are so picky that each one will only be milked over some precise time interval A…B (1 <= A <= B <= 1,000,000), which includes both times A and B. Obviously, FJ must create a reservation system to determine which stall each cow can be assigned for her milking time. Of course, no cow will share such a private moment with other cows.

Help FJ by determining:

  • The minimum number of stalls required in the barn so that each cow can have her private milking period
  • An assignment of cows to these stalls over time

Many answers are correct for each test dataset; a program will grade your answer.

Input

Line 1: A single integer, N

Lines 2…N+1: Line i+1 describes cow i’s milking interval with two space-separated integers.

Output

Line 1: The minimum number of stalls the barn must have.

Lines 2…N+1: Line i+1 describes the stall to which cow i will be assigned for her milking period.

Sample Input

51 102 43 65 84 7

Sample Output

412324

Hint

Explanation of the sample:

Here’s a graphical schedule for this output:

Time     1  2  3  4  5  6  7  8  9 10Stall 1 c1>>>>>>>>>>>>>>>>>>>>>>>>>>>Stall 2 .. c2>>>>>> c4>>>>>>>>> .. ..Stall 3 .. .. c3>>>>>>>>> .. .. .. ..Stall 4 .. .. .. c5>>>>>>>>> .. .. ..

Other outputs using the same number of stalls are possible.

题解

这个工作有时间,必须拿最小的开始时间去碰已经在牛棚工作结束的最小时间,中间的空隙最小,浪费的时间也最少,需要排序之后,拿优先队列让牛棚工作结束时间最小排前面。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#include<stack>#include<set>#include <cstring>#include<queue>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e5 + 10;long long gcd(long long a, long long b) {    return b ? gcd(b, a % b) : a;}struct no {    int a;    int b;    int c;    int d;    bool operator<(const no &aa) const {        if (b == aa.b)            return a < aa.a;        return b > aa.b;    }} wrc[N];int zqq[N];bool cmp(no aa, no bb) {    if (aa.a == bb.a)        return aa.b < bb.b;    return aa.a < bb.a;}bool cmpc(no aa, no bb) {    return aa.c < bb.c;}int main() {    IOS;    int n;    priority_queue<no> q;    cin >> n;    for (int i = 1; i <= n; i++) {        cin >> wrc[i].a >> wrc[i].b;        wrc[i].c = i;    }    sort(wrc + 1, wrc + 1 + n, cmp);    for (int i = 1; i <= n; i++) {        if (!q.empty() && q.top().b < wrc[i].a) {            wrc[i].d = q.top().d;            q.pop();        } else wrc[i].d = (int) q.size();        q.push(wrc[i]);    }    cout << q.size() << endl;    sort(wrc + 1, wrc + 1 + n, cmpc);    int k = 1;    for (int i = 1; i <= n; i++) {        if (!zqq[wrc[i].d])            zqq[wrc[i].d] = k++;        cout << zqq[wrc[i].d] << endl;    }    return 0;}//6//1 3 5 7 6 9 10 11 8 12 4 13

N

N

Farmer John is assigning some of his N (1 <= N <= 25,000) cows to do some cleaning chores around the barn. He always wants to have one cow working on cleaning things up and has divided the day into T shifts (1 <= T <= 1,000,000), the first being shift 1 and the last being shift T.

Each cow is only available at some interval of times during the day for work on cleaning. Any cow that is selected for cleaning duty will work for the entirety of her interval.

Your job is to help Farmer John assign some cows to shifts so that (i) every shift has at least one cow assigned to it, and (ii) as few cows as possible are involved in cleaning. If it is not possible to assign a cow to each shift, print -1.

Input

* Line 1: Two space-separated integers: N and T

* Lines 2…N+1: Each line contains the start and end times of the interval during which a cow can work. A cow starts work at the start time and finishes after the end time.

Output

* Line 1: The minimum number of cows Farmer John needs to hire or -1 if it is not possible to assign a cow to each shift.

Sample Input

3 101 73 66 10

Sample Output

2

Hint

This problem has huge input data,use scanf() instead of cin to read data to avoid time limit exceed.

INPUT DETAILS:

There are 3 cows and 10 shifts. Cow #1 can work shifts 1…7, cow #2 can work shifts 3…6, and cow #3 can work shifts 6…10.

OUTPUT DETAILS:

By selecting cows #1 and #3, all shifts are covered. There is no way to cover all the shifts using fewer than 2 cows.

题解

排序,按照开始时间排序,选一个减去前一个结尾最长的,也就是新加的最长的,这样就能保证工作的区间最长,用的牛也就最少了。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e5 + 10;struct no {    int a;    int b;} wrc[N];bool cmp(no aa, no bb) {    if (aa.a == bb.a)        return aa.b > bb.b;    return aa.a < bb.a;}int main() {    IOS;    int n, m;    cin >> n >> m;    for (int i = 1; i <= n; i++)        cin >> wrc[i].a >> wrc[i].b;    int ans = 1;    sort(wrc + 1, wrc + 1 + n, cmp);    if (wrc[1].a != 1) {        cout << -1 << endl;        return 0;    }    int p, k;    for (int i = 1; i <= n;) {        k = i + 1;        p = wrc[i].b;        for (int j = k; j <= n; j++) {            if (wrc[j].a <= wrc[i].b + 1) {                if (wrc[j].b > p) {//                    cout << wrc[j].b << " " << p << endl;                    k = j;                    p = wrc[j].b;                }            } else break;        }        if (p != wrc[i].b)            ans++;        if (p >= m)            break;        if (p == wrc[i].b)            break;        i = k;    }//    cout << p << endl;    if (p < m)        cout << -1 << endl;    else        cout << ans << endl;    return 0;}//3 10//1 7//2 10//3 9

O

O

Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.

Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person’s weight is w**i, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.

Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.

Help the party to determine minimum possible total instability!

Input

The first line contains one number n (2 ≤ n ≤ 50).

The second line contains 2·n integer numbers w1, w2, …, w2n, where w**i is weight of person i (1 ≤ w**i ≤ 1000).

Output

Print minimum possible total instability.

Examples

Input

21 2 3 4

Output

1

Input

41 3 4 6 3 4 100 200

Output

5

题解

排序后,暴力选择两个人,算出答案,比对最小的答案。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;int a[150];int b[150];int main() {    int n;    cin >> n;    int m = -1;    for (int i = 1; i <= 2 * n; i++)        cin >> a[i];    for (int i = 1; i <= 2 * n; i++) {        for (int j = i + 1; j <= 2 * n; j++) {            int s = 0;            for (int k = 1; k <= 2 * n; k++)                b[k] = a[k];            b[j] = b[i] = 1001;            sort(b + 1, b + 2 * n + 1);            for (int k = 2; k <= 2 * n - 2; k += 2)                s += b[k] - b[k - 1];            m = (m == -1 || s < m) ? s : m;        }    }    cout << m << endl;    return 0;}

P

P

Little Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern.

An unpainted tile should be painted Red if it’s index is divisible by a and an unpainted tile should be painted Blue if it’s index is divisible by b. So the tile with the number divisible by a and b can be either painted Red or Blue.

After her painting is done, she will get p chocolates for each tile that is painted Red and q chocolates for each tile that is painted Blue.

Note that she can paint tiles in any order she wants.

Given the required information, find the maximum number of chocolates Joty can get.

Input

The only line contains five integers n, a, b, p and q (1 ≤ n, a, b, p, q ≤ 109).

Output

Print the only integer s — the maximum number of chocolates Joty can get.

Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

Examples

Input

5 2 3 12 15

Output

39

Input

20 2 3 3 5

Output

51

题解

直接算n个中有多少个a整除的,和b能整除的,然后算出两个共同的,减去少的哪个,留下多的,就是答案。】

AC代码

#include <iostream>#include<algorithm>#include<cmath>#include<stack>#include<set>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;long long gcd(long long a, long long b) {    return b ? gcd(b, a % b) : a;}int main() {    IOS;    long long n, a, b, p, q;    cin >> n >> a >> b >> p >> q;    long long gg = a / gcd(a, b) * b;    long long aa = n / a * p;    long long bb = n / b * q;    long long s = aa + bb - (n / gg) * min(p, q);    cout << s << endl;    return 0;}

Q

Q

There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.

Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one.

Can you determine who will be each person’s teammate?

Input

There are 2n lines in the input.

The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed.

The i-th line (i > 1) contains i - 1 numbers a**i1, a**i2, … , a**i(i - 1). Here a**ij (1 ≤ a**ij ≤ 106, all a**ij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)

Output

Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.

Examples

Input

261 23 4 5

Output

2 1 4 3

Input

34870603831 161856845957 794650 97697783847 50566 691206 498447698377 156232 59015 382455 626960

Output

6 5 4 3 2 1

Note

In the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.

题解

找最大的,然后把跟这个两个有关的全部变成0,再找现在第二大的。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e5 + 10;struct no {    int a;    int b;};int wrc[805][805];int zqq[405];bool cmp(no aa, no bb) {    if (aa.a == bb.a)        return aa.b < bb.b;    return aa.a < bb.a;}int main() {    IOS;    int n;    cin >> n;    for (int i = 2; i <= 2 * n; i++) {        for (int j = 1; j < i; j++) {            cin >> wrc[i][j];//            wrc[j][i] = wrc[i][j];        }    }    int x, y;    for (int h = 1; h <= n; h++) {        int k = 0;        for (int i = 2; i <= 2 * n; i++) {            for (int j = 1; j < i; j++) {                if (wrc[i][j] > k) {                    k = wrc[i][j];                    y = i;                    x = j;                }            }        }        zqq[y] = x;        zqq[x] = y;        for (int j = x; j <= 2 * n; j++) {            wrc[j][x] = 0;        }        for (int j = 1; j <= x; j++)            wrc[x][j] = 0;        for (int j = 1; j <= y; j++) {            wrc[y][j] = 0;        }        for (int j = y; j <= 2 * n; j++) {            wrc[j][y] = 0;        }    }    for (int i = 1; i <= 2 * n; i++)        cout << zqq[i] << " ";    cout << endl;    return 0;}

R

R

Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly a**i kilograms of meat.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QMqG3Ut3-1625225468809)(https://vj.z180.cn/46ba1382db92b60375e3f8365ad6bff6?v=1624567187)]

There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for p**i dollars per kilogram. Malek knows all numbers a1, …, a**n and p1, …, p**n. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.

Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days.

Input

The first line of input contains integer n (1 ≤ n ≤ 105), the number of days.

In the next n lines, i-th line contains two integers a**i and p**i (1 ≤ a**i, p**i ≤ 100), the amount of meat Duff needs and the cost of meat in that day.

Output

Print the minimum money needed to keep Duff happy for n days, in one line.

Examples

Input

31 32 23 1

Output

10

Input

31 32 13 2

Output

8

Note

In the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.

In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.

题解

把之前价格少的存下来就行,根据数量算出总价格

AC代码

#include <iostream>#include<algorithm>#include<cmath>#include<stack>#include<set>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;long long gcd(long long a, long long b) {    return b ? gcd(b, a % b) : a;}int a[N];int main() {    IOS;    int n, k, p = 0, g;    cin >> n;    for (int i = 1; i <= n; i++) {        cin >> a[i] >> k;        g = i == 1 ? k : min(g, k);        p += a[i] * g;    }    cout << p << endl;    return 0;}

S

S

Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2w**i pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there’s no more weight left. Malek asked her to minimize the number of steps.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Jsbn1dpH-1625225468810)(https://vj.z180.cn/86a583f71a5f9b1736f30dd021f3ebee?v=1624447962)]

Duff is a competitive programming fan. That’s why in each step, she can only lift and throw away a sequence of weights 2a1, …, 2a**k if and only if there exists a non-negative integer x such that 2a1 + 2a2 + … + 2a**k = 2x, i. e. the sum of those numbers is a power of two.

Duff is a competitive programming fan, but not a programmer. That’s why she asked for your help. Help her minimize the number of steps.

Input

The first line of input contains integer n (1 ≤ n ≤ 106), the number of weights.

The second line contains n integers w1, …, w**n separated by spaces (0 ≤ w**i ≤ 106 for each 1 ≤ i ≤ n), the powers of two forming the weights values.

Output

Print the minimum number of steps in a single line.

Examples

Input

51 1 2 3 3

Output

2

Input

40 1 2 3

Output

4

Note

In the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it’s not possible to do it in one step because their sum is not a power of two.

In the second sample case: The only optimal way is to throw away one weight in each step. It’s not possible to do it in less than 4 steps because there’s no subset of weights with more than one weight and sum equal to a power of two.

题解

2a+2a = 2*2a = 2a+1

就这样转化下去,两个一样的就转为下一个,最后看剩多少个。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;deque<int> q;int a[N];int main() {    IOS;    int n, m;    cin >> n;    for (int i = 1; i <= n; i++) {        cin >> m;        a[m]++;    }//    sort(a + 1, a + 1 + n);    int ans = 0;    for (int i = 0; i < 1e6; i++) {        a[i + 1] += a[i] / 2;        if (a[i] % 2)            ans++;    }    int k = 1e6;    while (a[k]) {        if (a[k] % 2)            ans++;        a[k] /= 2;    }    cout << ans << endl;    return 0;}

T

T

One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let’s assume that Misha chose number m, and Andrew chose number a.

Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen with the same probability), after which the winner is the player, whose number was closer to c. The boys agreed that if m and a are located on the same distance from c, Misha wins.

Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number n. You need to determine which value of a Andrew must choose, so that the probability of his victory is the highest possible.

More formally, you need to find such integer a (1 ≤ a ≤ n), that the probability that [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eD6BKqzA-1625225468811)(https://vj.z180.cn/47b043fac84ce662581f8f63d2203e78?v=1624349343)] is maximal, where c is the equiprobably chosen integer from 1 to n (inclusive).

Input

The first line contains two integers n and m (1 ≤ m ≤ n ≤ 109) — the range of numbers in the game, and the number selected by Misha respectively.

Output

Print a single number — such value a, that probability that Andrew wins is the highest. If there are multiple such values, print the minimum of them.

Examples

Input

3 1

Output

2

Input

4 3

Output

2

Note

In the first sample test: Andrew wins if c is equal to 2 or 3. The probability that Andrew wins is 2 / 3. If Andrew chooses a = 3, the probability of winning will be 1 / 3. If a = 1, the probability of winning is 0.

In the second sample test: Andrew wins if c is equal to 1 and 2. The probability that Andrew wins is 1 / 2. For other choices of a the probability of winning is less.

题解

要选择的值比另一个人选择的值更靠近中间一个,要是那个人的值在中间,就往左边一个,要求最小值。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;int a[150];int b[150];int main() {    long long n, m;    scanf("%lld%lld", &n, &m);    if (n == 1)        printf("1\n");    else if (2 * m >= n + 1)        printf("%lld\n", m - 1);    else        printf("%lld\n", m + 1);    return 0;}

U

U

Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.

Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.

Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

Input

First line of the input contains a single integer n (1 ≤ n ≤ 2·105), the length of the string that Andreid has.

The second line contains the string of length n consisting only from zeros and ones.

Output

Output the minimum length of the string that may remain after applying the described operations several times.

Examples

Input

41100

Output

0

Input

501010

Output

1

Input

811101111

Output

6

Note

In the first sample test it is possible to change the string like the following: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZFB6k2pn-1625225468811)(https://vj.z180.cn/4c29e2691ab98b94d6c5e5f4f4e1a18c?v=1624321070)].

In the second sample test it is possible to change the string like the following: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xx2OGP7u-1625225468812)(https://vj.z180.cn/75e9583ea06b70666af0345b78c07c2b?v=1624321070)].

In the third sample test it is possible to change the string like the following: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KQ6avZj5-1625225468812)(https://vj.z180.cn/45476f599b509e877534062a9b7ca1f7?v=1624321070)].

题解

分别计算01个数,然后看差值就是答案

AC代码

#include <iostream>#include<algorithm>#include<cmath>#include<stack>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;stack<char> q;int main() {    int n;    string s;    cin >> n >> s;    for (char i : s) {        if (!q.empty() && q.top() != i)            q.pop();        else q.push(i);    }    cout << q.size() << endl;    return 0;}

V

V

Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.

During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.

You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.

Input

The first line contains a single integer n — the number of items (1 ≤ n ≤ 105).

The second line contains n numbers a1, a2, …, a**n (1 ≤ a**i ≤ 105) — the initial inventory numbers of the items.

Output

Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.

Examples

Input

31 3 2

Output

1 3 2 

Input

42 2 3 3

Output

2 1 3 4 

Input

12

Output

1 

Note

In the first test the numeration is already a permutation, so there is no need to change anything.

In the second test there are two pairs of equal numbers, in each pair you need to replace one number.

In the third test you need to replace 2 by 1, as the numbering should start from one.

题解

记录个数,不止一个的,就按照没有用过的顺序一一修改。

AC代码

#include <iostream>#include<algorithm>#include<cmath>#include<stack>#include<set>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;int a[N];int b[N];int c[N];int main() {    IOS;    int n, k = 1;    cin >> n;    for (int i = 1; i <= n; i++) {        cin >> a[i];        b[a[i]]++;    }    for (int i = 1; i <= n; i++) {        if (!b[i])            c[k++] = i;    }    k = 1;    for (int i = 1; i <= n; i++) {        if (a[i] > n || b[a[i]] > 1) {            b[a[i]]--;            a[i] = c[k++];            b[a[i]]++;        }    }    for (int i = 1; i <= n; i++)        cout << a[i] << " ";    cout << endl;    return 0;}

W

W

Vanya has a scales for weighing loads and weights of masses w0, w1, w2, …, w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.

Input

The first line contains two integers w, m (2 ≤ w ≤ 109, 1 ≤ m ≤ 109) — the number defining the masses of the weights and the mass of the item.

Output

Print word ‘YES’ if the item can be weighted and ‘NO’ if it cannot.

Examples

Input

3 7

Output

YES

Input

100 99

Output

YES

Input

100 50

Output

NO

Note

Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1.

Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100.

Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input.

题解

他是用w1到w100次方,因为两边都可以加,所以简化意思都是可以加减都行,就看m能不能用w进制表示,但是都只能有一个。

减法表示为wi+1 - wi = (w-1)wi

这样转化了之后,就看最后这些位是不是1,0,w-1

AC代码

#include <iostream>
#include<algorithm>
#include<cmath>
#include<stack>
#include<set>

#define IOS  ios::sync_with_stdio(false)
#define endl "\n"
#define PI acos(-1)
using namespace std;
const int N = 1e6 + 10;
int a[N];
int b[N];
int c[N];

int main() {
    IOS;
    int n, k = 1;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        b[a[i]]++;
    }
    for (int i = 1; i <= n; i++) {
        if (!b[i])
            c[k++] = i;
    }
    k = 1;
    for (int i = 1; i <= n; i++) {
        if (a[i] > n || b[a[i]] > 1) {
            b[a[i]]--;
            a[i] = c[k++];
            b[a[i]]++;
        }
    }
    for (int i = 1; i <= n; i++)
        cout << a[i] << " ";
    cout << endl;
    return 0;
}

X

X

Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.

In total the table Arthur bought has n legs, the length of the i-th leg is l**i.

Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number d**i — the amount of energy that he spends to remove the i-th leg.

A table with k legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with 5 legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths.

Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.

Input

The first line of the input contains integer n (1 ≤ n ≤ 105) — the initial number of legs in the table Arthur bought.

The second line of the input contains a sequence of n integers l**i (1 ≤ l**i ≤ 105), where l**i is equal to the length of the i-th leg of the table.

The third line of the input contains a sequence of n integers d**i (1 ≤ d**i ≤ 200), where d**i is the number of energy units that Arthur spends on removing the i-th leg off the table.

Output

Print a single integer — the minimum number of energy units that Arthur needs to spend in order to make the table stable.

Examples

Input

21 53 2

Output

2

Input

32 4 41 1 1

Output

0

Input

62 2 1 1 3 34 3 5 5 2 1

Output

8

题解

桌腿长度从小到大排序,从小开始选,大的全部被去除,保证自己是最大的,然后就是,小于这个腿长的只能为这个腿长的数量-1,多的砍掉最小的那几个就行了,使用标记数组。

AC代码

#include <iostream>#include<algorithm>#include <cstring>#include<cmath>#include<stack>#include<set>#include<queue>#define IOS  ios::sync_with_stdio(false)#define endl "\n"#define PI acos(-1)using namespace std;const int N = 1e6 + 10;struct no {    int y;    int x;//    bool operator<(const no &a) const {//        return x > a.x;//    }} wrc[N];int zqq[N];int cc[N];int ll[205];bool cmp(no aa, no bb) {    return aa.y < bb.y;}int main() {    IOS;//    priority_queue<no> q, qq;    int n;    cin >> n;    for (int i = 1; i <= n; i++) {        cin >> wrc[i].y;        cc[wrc[i].y]++;    }    for (int i = 1; i <= 1e5; i++)        cc[i] += cc[i - 1];    for (int i = 1; i <= n; i++)        cin >> wrc[i].x;    sort(wrc + 1, wrc + 1 + n, cmp);    for (int i = n; i >= 1; i--)        zqq[wrc[i].y] += wrc[i].x;    for (int i = 1e5; i >= 1; i--)        zqq[i] += zqq[i + 1];    long long ans = -1;    int k = 0;    for (int i = 1; i <= n; i++) {        if (wrc[i].y != k) {            if (cc[wrc[i].y] - cc[wrc[i].y - 1] > cc[wrc[i].y] / 2)                ans = ans == -1 ? (long long) zqq[wrc[i].y + 1] : min(ans, (long long) zqq[wrc[i].y + 1]);            else {                long long zl = 0;                int m = cc[wrc[i].y - 1] - (cc[wrc[i].y] - cc[wrc[i].y - 1] - 1);                int qq = 1;//                cout << "########" << endl;//                cout << "i " << wrc[i].y << endl;                for (int j = 1; j <= 200 && qq <= m; j++) {//                    if (ll[j])//                        cout << j << endl;                        if (qq + ll[j] > m)                            zl += j * (m - qq + 1);                        else zl += j * ll[j];//                    cout << "@" << zl << endl;                    qq += ll[j];                }                ans = ans == -1 ? (long long) zqq[wrc[i].y + 1] : min(ans, (long long) zqq[wrc[i].y + 1] + zl);//                cout << "#   " << ans << endl;            }            k = wrc[i].y;        }        ll[wrc[i].x]++;    }    cout << ans << endl;    return 0;}

Y

Y

Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.

Amr has n different types of chemicals. Each chemical i has an initial volume of a**i liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.

To do this, Amr can do two different kind of operations.

  • Choose some chemical i and double its current volume so the new volume will be 2a**i
  • Choose some chemical i and divide its volume by two (integer division) so the new volume will be [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Epre9SaX-1625225468813)(https://vj.z180.cn/5438b50e97e618c112409c5433ed3cd5?v=1624190773)]

Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?

Input

The first line contains one number n (1 ≤ n ≤ 105), the number of chemicals.

The second line contains n space separated integers a**i (1 ≤ a**i ≤ 105), representing the initial volume of the i-th chemical in liters.

Output

Output one integer the minimum number of operations required to make all the chemicals volumes equal.

Examples

Input

34 8 2

Output

2

Input

33 5 6

Output

5

Note

In the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.

In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 1.

题解

把数字能跑到的数字全记录下来,再记录次数, 然后看看哪个能跑完,而且步数最小。

AC代码

#include <iostream>
#include<algorithm>
#include <cstring>
#include<cmath>
#include<stack>
#include<set>
#include<queue>
#include<map>
#include<sstream>

#define IOS  ios::sync_with_stdio(false)
#define endl "\n"
#define PI acos(-1)
#define INF 0x3f3f3f3f
using namespace std;
const int N = 1e5 + 10;
int num[N];
int k[N];
int zqq[N];

int main() {
//    IOS;
    int n, m = 0;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> num[i];
        m = max(num[i], m);
    }
    for (int i = 1; i <= n; i++) {
        int p = num[i];
        int v = 0;
        p = num[i];
        while (p <= m) {
            zqq[p] += v;
            k[p]++;
//            cout << "# " << p << endl;
            p *= 2;
            v++;
        }
        v = 0;
        p = num[i];
        while (p > 1) {
            v++;
            int pp = p / 2;
            int vv = v;
            if (p % 2) {
                while (pp <= m && pp > 0) {
                    pp *= 2;
                    if (pp > m)
                        break;
                    vv++;
                    zqq[pp] += vv;
                    k[pp]++;
                }
            }
            p /= 2;
            k[p]++;
            zqq[p] += v;
//            cout << "##########" << endl;
//            cout << i << endl;
//            cout << p << endl;
//            cout << zqq[p] << endl;
        }
    }
    int p = INF;
    for (int i = 1; i <= m; i++) {
//        cout << zqq[i] << endl;
        if (k[i] >= n)
            p = min(zqq[i], p);
    }
    cout << p << endl;
    return 0;
}

Z

Z

Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:

Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one.

To be more clear, consider all integer sequence with length k (a1, a2, …, a**k) with [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qpmQvAxV-1625225468814)(https://vj.z180.cn/79b28461c48786f0c9afa0e57e56be1b?v=1624485299)]. Give a value [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MZW99D3X-1625225468814)(https://vj.z180.cn/fb216ac8362c5f999ae19b0050483da8?v=1624485299)] to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest.

For definitions of powers and lexicographical order see notes.

Input

The first line consists of two integers n and k (1 ≤ n ≤ 1018, 1 ≤ k ≤ 105) — the required sum and the length of the sequence.

Output

Output “No” (without quotes) in a single line if there does not exist such sequence. Otherwise, output “Yes” (without quotes) in the first line, and k numbers separated by space in the second line — the required sequence.

It is guaranteed that the integers in the answer sequence fit the range [ - 1018, 1018].

Examples

Input

23 5

Output

Yes3 3 2 1 0 

Input

13 2

Output

No

Input

1 2

Output

Yes-1 -1 

Note

Sample 1:

23 + 23 + 22 + 21 + 20 = 8 + 8 + 4 + 2 + 1 = 23

Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest.

Answers like (4, 1, 1, 1, 0) do not have the minimum y value.

Sample 2:

It can be shown there does not exist a sequence with length 2.

Sample 3:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a7yCoCtQ-1625225468815)(https://vj.z180.cn/95cc020b6fa5eb8bfa7876489cc8e811?v=1624485299)]

Powers of 2:

If x > 0, then 2x = 2·2·2·…·2 (x times).

If x = 0, then 2x = 1.

If x < 0, then [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JTRN9Bvb-1625225468816)(https://vj.z180.cn/1137329d9b05a2fbe390a3d0f4a90ad6?v=1624485299)].

Lexicographical order:

Given two different sequences of the same length, (a1, a2, … , a**k) and (b1, b2, … , b**k), the first one is smaller than the second one for the lexicographical order, if and only if a**i < b**i, for the first i where a**i and b**i differ.

题解

化为2进制,然后把最大的变小,如果要是全部变小的时候装不下了,就不变了最大的了,不断去把最小的变小,才能在最大数字最小的基础上让字典序变大。

AC代码

#include <iostream>
#include<algorithm>
#include <cstring>
#include<cmath>
#include<stack>
#include<set>
#include<queue>
#include<map>

#define IOS  ios::sync_with_stdio(false)
#define endl "\n"
#define PI acos(-1)
using namespace std;
const int N = 1e5 + 10;
map<int, int> zqq;

int main() {
    IOS;
    long long p, w, n;
    cin >> p >> n;
    w = p;
    int r = 0;
    long long k = 0;
    while (w) {
        k += w % 2;
        zqq[r++] = w % 2;
        w /= 2;
    }
    r--;
//    cout << r << endl;
    if (k > n)
        cout << "No" << endl;
    else {
        cout << "Yes" << endl;
        int g;
        for (int i = r; k < n; i--) {
            g = i;
            if (k + zqq[i] > n) {
                break;
            } else {
                zqq[i - 1] += zqq[i] * 2;
                k += zqq[i];
                zqq[i] = 0;
            }
        }
        g = min(--g, 0);
        int gg = g;
        if (k != n) {
            while (!zqq[gg])
                gg++;
            zqq[gg]--;
            gg--;
        }
        int s;
        for (int i = r; i >= g; i--)
            for (int j = 1; j <= zqq[i]; j++)
                cout << i << " ";
        for (int i = 0; i < n - k; i++) {
            s = gg - i;
            cout << s << " ";
        }
//        cout << gg - i << " ";
        if (n == k)
            cout << endl;
        else
            cout << s << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值