PTA甲级
1048 Find Coins
简单的二分,可以使用lower_bound找到大于等于的第一个下标
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;
int n , m;
int a[N];
int main()
{
cin >> n >> m;
for(int i = 0;i < n;i ++)
cin >> a[i];
sort(a , a + n);
bool f = true;
for(int i = 0;i < n;i ++)
{
int target = m - a[i];
// >= target
int idx = lower_bound(a + i + 1 , a + n , target) - a;
if(idx < n && a[idx] == target)
{
f = false;
cout << a[i] << " " << target << endl;
break;
}
}
if(f) cout << "No Solution";
return 0;
}
1052 Linked List Sorting
链表排序,先通过指针穿起来之后,排序即可
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 1e6 + 10;
struct node
{
int address;
int key;
int next;
};
vector<node>v(N);
bool cmp(node a , node b)
{
return a.key < b.key;
}
int n , start;
int main()
{
scanf("%d %d" ,&n ,&start);
if(start == -1)
{
cout << "0 -1" << endl;
return 0;
}
while(n --)
{
int a , b , c;
scanf("%d %d %d" ,&a ,&b ,&c);
v[a] = {a , b , c};
}
vector<node>res;
// 需要先串起来,因为有的点不在链表中
while(start != -1)
{
res.push_back(v[start]);
start = v[start].next;
}
sort(res.begin() , res.end() , cmp);
printf("%d %05d\n" , res.size() , res[0].address);
for(int i = 0;i < res.size();i ++)
{
printf("%05d %d " ,res[i].address , res[i].key);
if(i + 1 < res.size()) printf("%05d" , res[i + 1].address);
else printf("-1");
puts("");
}
return 0;
}
1053 Path of Equal Weight
dfs图的遍历
#include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;
const int N = 1010;
int n , m , k;
int weight[N];
// vector<int>g[N];
unordered_map<int , vector<int>>g;
unordered_map<int , vector<int>>path;
vector<vector<int>>res;
int cnt = 0;
void dfs(int u , int total , vector<int>&temp)
{
if(!g[u].size())
{
if(total == k) path[cnt ++] = temp;
return ;
}
for(int i : g[u])
{
temp.push_back(weight[i]);
dfs(i , total + weight[i] , temp);
temp.pop_back();
}
}
bool cmp(vector<int>&a , vector<int>&b)
{
for(int i = 0;i < a.size() && i < b.size();i ++)
{
if(a[i] > b[i]) // a > b
return true;
else if(a[i] < b[i]) // a < b
return false;
}
return a.size() > b.size();
}
int main()
{
scanf("%d %d %d" ,&n ,&m ,&k);
for(int i = 0;i < n;i ++)
scanf("%d" ,&weight[i]);
for(int i = 0;i < m;i ++)
{
int id , k;
scanf("%d %d" ,&id ,&k);
for(int j = 0;j < k;j ++)
{
int w;
scanf("%d" ,&w);
g[id].push_back(w);
}
}
vector<int>temp{weight[0]};
dfs(0 , weight[0] , temp);
for(int i = 0;i < cnt;i ++)
res.push_back(path[i]);
sort(res.begin() , res.end() , cmp);
for(auto i : res)
{
for(int j = 0;j < i.size();j ++)
{
if(j) printf(" ");
printf("%d" ,i[j]);
}
puts("");
}
return 0;
}