首页 > 代码库 > 无聊刷题1

无聊刷题1

一级算法简单题。。

51nod 1001 数组中和等于K的数对

题解:排序再二分搜索能过,但有个复杂度为O(n)的方法:如果a[i]>=k/2,则让a[i]=k-a[i],排序后直接判断相邻两项是否相等即可。

#include<stdio.h>#include<algorithm>using namespace std;int main(){    int a[50001], n, k, i,  f= 0;    scanf("%d%d", &k, &n);    for(i = 0;i < n;++i){        scanf("%d", &a[i]);        if(a[i] >= k/2)  a[i] = k-a[i];    }    sort(a, a+n);    for(i = 0;i < n-1;++i){        if(a[i] == a[i+1]){            printf("%d %d\n", a[i], k-a[i]);            i++; f = 1;        }    }    if(!f) printf("No Solution\n");    return 0;}

51nod 1002 数塔取数问题

最简单的dp

#include<stdio.h>#include<algorithm>using namespace std;int a[501][501];int main(){    int n, i, j, f = 0;    scanf("%d", &n);    for(i = 0;i < n;++i)        for(j = 0;j <= i;++j) scanf("%d", &a[i][j]);    for(i = n - 2;i >= 0;--i)        for(j = 0;j <= i;++j)        a[i][j] += max(a[i+1][j], a[i+1][j+1]);    printf("%d\n", a[0][0]);    return 0;}

51nod 1003 阶乘后面0的数量

题解:要求n!末尾0的个数,只要求出1~n各个数的因子中5的个数(2的个数远多于5)

#include<stdio.h>int main(){    int n, m=0;    scanf("%d", &n);    while(n >= 5){        m += n/5;        n /= 5;    }    printf("%d\n", m);    return 0;}

51nod 1004 n^n的末位数字

题解:找规律,末位数字:n^1,n^2,n^3,n^4,n^5(=n^1)….周期为4

#include<stdio.h>#include<math.h>int main(){    int n, a, b;    scanf("%d", &n);    a = n % 10;    b = n % 4;    if(b == 0) b = 4;    b = pow(a, b);    printf("%d\n", b % 10);    return 0;}

无聊刷题1