pat 甲级 1048 Find Coins

自己第一次写的代码,有一个点超时

#include 
#include 
#include 
#include 

using namespace std;

int a, b;
vector<int> coin;
int n, m;

int main(){

    scanf("%d%d",&n,&m);
    for(int i=0; iint x, y = 0;
        scanf("%d",&x);
        if(x>=m) continue;
        else {
            coin.push_back(x);
        }
    }
    if(coin.size() == 0) {
        printf("No Solution");
        return 0;
    }

    sort(coin.begin(),coin.end());
    int l = coin.size();
    for(int i=0; ifor(int j=l-1; j>i; j--){
            if(coin[i]+coin[j] < m) break;
            if(coin[i]+coin[j] == m) {
                printf("%d %d",coin[i],coin[j]);
                return 0;
            }

        }
    }
    printf("No Solution");

    return 0;
}

目前自己的代码还没想出来可以优化的地方
膜拜大佬们的代码!太精巧了

#include 
#include 
#include 
#include 

using namespace std;

int a, b;
int coin[1100];
int n, m;

int main(){

    scanf("%d%d",&n,&m);
    for(int i=0; iscanf("%d",&a);
        coin[a]++;
    }
    for(int i=1; i<1001; i++){
        if(coin[i]){
            coin[i]--; //16 = 8 + 8 情况 
            if(coin[m-i] && m > i){
                printf("%d %d",i,m-i);
                return 0;
            }
            coin[i]++;
        }

    }

    printf("No Solution");

    return 0;
}

你可能感兴趣的:(pat)