zoukankan      html  css  js  c++  java
  • codevs1553 互斥的数

    1553 互斥的数

     
     
     
    题目描述 Description

    有这样的一个集合,集合中的元素个数由给定的N决定,集合的元素为N个不同的正整数,一旦集合中的两个数x,y满足y = P*x,那么就认为x,y这两个数是互斥的,现在想知道给定的一个集合的最大子集满足两两之间不互斥。

    输入描述 Input Description

    输入有多组数据,每组第一行给定两个数N和P(1<=N<=10^5, 1<=P<=10^9)。接下来一行包含N个不同正整数ai(1<=ai<=10^9)。

    输出描述 Output Description

    输出一行表示最大的满足要求的子集的元素个数。

    样例输入 Sample Input

    4 2

    1 2 3 4

    样例输出 Sample Output

    3

    思路

    贪心思想+map实现 
    找出不互质的数的集合,就是把互斥的数删去,那么当有两个互斥的数时,删掉哪一个呢?删掉后面的。为什么?当删掉后面的数时,这个数前面的会入选,这个数后面的与它互斥的数也会入选,因为每个数都是不同的。 
    举个例子: 
    3 2 
    1 2 4 
    当枚举到1时 会发现1和2有冲突 
    我们毫不犹豫的删去2 这样4才能也被选入 
    样例2 
    4 2 
    1 2 4 8 
    当我们枚举到1时 还是发现1和2有冲突 
    还是删去2 这样4能被选入 而8必须被删去

    #include<iostream>
    #include<algorithm>
    #include<map>
    using namespace std;
    const int maxn=100010;
    int n,p,a[maxn],ans;
    map<int,int>flag;
    int main()
    {
        cin>>n>>p;
        for(int i=1;i<=n;i++)
        cin>>a[i];
        sort(a+1,a+n+1);
        for(int i=1;i<=n;i++)
            if(flag[a[i]]==0)
            {
                ans++;
                flag[a[i]*p]=1;
            }
        cout<<ans;
        return 0;
    }

    也可以用hash表代替map

    #include<iostream>
    #include<cstdio>
    #include<cstdlib>
    #include<algorithm>
    using namespace std;
    #define maxn 100010
    #define inf 23333
    int n,p,num,head[maxn];
    struct node{
        int to,pre;
    }e[maxn];
    int ans,a[maxn];
    bool find(int from,int x){
        for(int i=head[from];i;i=e[i].pre)
            if(e[i].to==x)return 1;
        return 0;
    }
    void add(int from,int to){
        e[++num].to=to;
        e[num].pre=head[from];
        head[from]=num;
    }
    int main(){
        scanf("%d%d",&n,&p);
        for(int i=1;i<=n;i++)scanf("%d",&a[i]);
        sort(a+1,a+n+1);
        for(int i=1;i<=n;i++){
            if(find(a[i]%inf,a[i]))continue;
            int w=a[i]*p;
            add(w%inf,w);
            ans++;
        }
        printf("%d",ans);
    }
  • 相关阅读:
    ARM应用笔记网址和常见问题
    ARM处理器中断处理的编程实现(转)
    altera_avalon_pio_regs.h中的函数意义
    keil 启动代码at91sam9260
    转载:"IF :DEF: EN_CRP"这一句是什么意思啊?
    Realview MDK中启动代码的配置详解
    转载 网络上的8051 free IP core资源
    keil下ARM启动代码分析视频
    SOPC方面的书籍
    NIOS的system.h解读PIO实现的LED灯和key
  • 原文地址:https://www.cnblogs.com/thmyl/p/6195394.html
Copyright © 2011-2022 走看看